我有以下資料框架:
df =structure(list(文本= c("Text 1"/span>。
"Text 2",
"Text 3",
"Text 4",>
"Text 5",>
"Text 6",>
"Text 7",>
"Text 8",>
"Text 9",>
"Text 10"
)。 E = c(1。 0。 0, 0。 0, 0, 0。 0, 0。 0)。 S = c(0。 0, 0。 1, 0,
0,/span> 1。 0, 0。 1)。 G = c(0。 1。 1, 0。 1, 1, 0。 1, 1, 0)), 行。 names = c("1"/span>,
"2", "3", "4"。 "5", "6", "7"。 "8",/span> "9"。 "10"), class = "data. frame")
文本 E S G
1 Text 1 1 0 0
2 Text 2 0 0 1
3 Text 3 0 0 1
4 文本 4 0 1 0
5 文本 5 0 0 1
6 Text 6 0 0 1
7 Text 7 0 1 0
8 Text 8 0 0 1
9 Text 9 0 0 1
10 Text 10 0 1 0
正如你現在看到的,我有3個列(E、S、G),其中1或0表示哪個文本屬于哪個列。我想得到的結果如下:
texts Class
1 Text 1 E
2 Text 2 G
3 Text 3 G
4 Text 4 S
5 Text 5 G
6 Text 6 G
7 Text 7 S
8 Text 8 G
9 Text 9 G
10 Text 10 S
有人能幫助我嗎?
謝謝!
uj5u.com熱心網友回復:
如果你在一行中只有一個1,比如在這個例子中,你可以在基礎R中使用max.col -
cbind(df[1]。 類= names(df)[-1][/span>max. col(df[/span>-1])])
# text class
#1 Text 1 E
#2 Text 2 G
#3 Text 3 G #2 Text 2 G
#4 Text 4 S #3 Text 3 G
#5 Text 5 G[/span
#6 Text 6 G #5 Text 6 G
#7 Text 7 S #6 Text 6 G
#8 Text 8 G #8 Text 8 G
#9 Text 9 G #8 Text 9 G
#10 Text 10 S
另一個data.table選項 -
library(data.table)
melt(setDT(df), id. vars = 'text)。 標點符號">[值 == 1][/span>
,value:= NULL][/span>gtools: :mixedorder(texts)]/span>
uj5u.com熱心網友回復:
分散到長,過濾為1,然后放棄額外的列
df %>%
pivot_longer(cols =E: G,names_to = 'Class) %>%
filter(value == 1) %>%
select(-value)
uj5u.com熱心網友回復:
使用ifelse
df$E = ifelse(df$E == 1。 "E", NA)
df$S = ifelse(df$S == 1。 "S", NA)
df$G = ifelse(df$G == 1, "G", NA) )
class = do. call(pmax, c(df[/span>-1]/span>。 na. rm=TRUE))
df = cbind.data。 frame(texts = df[。 1]/span>。 class = class)
文本 class
1 Text 1 E
2 Text 2 G
3 Text 3 G
4 Text 4 S
5 Text 5 G
6 Text 6 G
7 Text 7 S
8 Text 8 G
9 Text 9 G
10 Text 10 S
uj5u.com熱心網友回復:
我們可以在按行分組后使用c_across
library(dplyr)
df %>%。
rowwise%>%
transmute(texts, Class = names(. )[-1][/span>which。 max(c_across(E: G))]) %>%
解除組
輸出
# A tibble: 10 x 2
文本類
<chr> <chr>
1 Text 1 E
2 Text 2 G
3 Text 3 G
4 Text 4 S
5 Text 5 G
6 Text 6 G
7 Text 7 S
8 Text 8 G
9 Text 9 G
10 Text 10 S
或者使用pmap
library(purrr)
df %>%
transmute(texts, 類= pmap_chr(across(E: G),
~ names(/span>which. max(c(. ...))))
文本類
1 Text 1 E
2 Text 2 G
3 Text 3 G
4 Text 4 S
5 Text 5 G
6 Text 6 G
7 Text 7 S
8 Text 8 G
9 Text 9 G
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/322209.html
標籤:
