簡體   English   中英

拆分數據框的列以合並重復變量

[英]Splitting columns of a dataframe to merge a repetitive variable

我通常在這里發布的先前問題中找到一個答案,但是似乎找不到這個問題,因此這是我的處女題:

我有一個數據框,其中一列具有重復的值,我想拆分其他列,並且第一列中只有一個值,並且比原始數據框中的列多。

例:

df <- data.frame(test = c(rep(1:5,3)), time = sample(1:100,15), score = sample(1:500,15))

原始數據幀具有3列和15行。

它將變成一個具有5行的數據幀,並且這些列將分為7列:“ test”,“ time1”,“ time2”,“ time3”,“ score1”,score2”,“ score3”。

有誰知道如何做到這一點?

我認為將dcast與data.table-package中的rowid一起使用非常適合此任務:

library(data.table)
dcast(setDT(df), test ~ rowid(test), value.var = c('time','score'), sep = '')

結果:

   test time1 time2 time3 score1 score2 score3
1:    1    52     3    29     21    131     45
2:    2    79    44     6    119      1    186
3:    3    67    95    39     18    459    121
4:    4    83    50    40    493    466    497
5:    5    46    14     4    465      9     24

請嘗試以下方法:

df <- data.frame(test = c(rep(1:5,3)), time = sample(1:100,15), score = sample(1:500,15))

df$class <- c(rep('a', 5), rep('b', 5), rep('c', 5))


df <- split(x = df, f = df$class)

binded <- cbind(df[[1]], df[[2]], df[[3]])

binded <- binded[,-c(5,9)]


> binded
  test time score class time.1 score.1 class.1 time.2 score.2 class.2
1    1   40   404     a     57     409       b     70      32       c
2    2    5   119     a     32     336       b     93     177       c
3    3   20   345     a     44      91       b    100      42       c
4    4   47   468     a     60     265       b     24     478       c
5    5   16    52     a     38     219       b      3      92       c

請讓我知道這對你有沒有用!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM