简体   繁体   English

在R中的一列上分布多个列

[英]Spreading multiple columns over a column in R

Sorry because this question has been asked several times, but I'm still having trouble wrapping my head around this problem. 抱歉,因为已经问几次这个问题,但是我仍然无法解决这个问题。

So I have a dataframe, of the form: 所以我有一个形式的数据框:

ID Val Type
1  10    A
2  11    A
2  10    C
3  10    B
3  12    C
4   9    B

It's not much help but you can use 并没有太大帮助,但您可以使用

library(tidyr)
test <- data.frame(ID = c(1,2,2,3,3,4), 
                   Val = c(10,11,10,10,12,9), 
                   Type = c('A', 'A', 'C', 'B', 'C', 'B'))

I would like to split it to obtain: 我想将其拆分为:

ID A.Type B.Type C.Type A.Val B.Val C.Val
1    1     0       0     10    0     0
2    1     0       1     11    0    10
3    0     1       1      0   10    12
4    0     0       0      0    9     0

I know how to get columns 1:4 using: 我知道如何让列1:4使用:

table(test[, c(1, 3)]) %>% as.data.frame() %>% spread(Type, Freq)

It's the last three I need help with because in the actual data-frame values are continuous and table can not be used. 这是我需要帮助的最后三个,因为在实际的数据帧中值是连续的并且不能使用table

You are trying to reshape your data with multiple value variables where the ones are actually implicit, so in order to get the type_... columns, you will need to create a new type variable with ones and then use dcast from data.table package: 您正在尝试与多个值的变量,其中的人实际上是隐含重塑你的数据,所以为了获得type_...列,您将需要创建一个新的变量类型与那些然后用dcastdata.table包:

library(data.table)
setDT(test)
dcast(test[, type := 1][], ID ~ Type, value.var = c("type", "Val"),fill = 0)
#    ID type_A type_B type_C Val_A Val_B Val_C
# 1:  1      1      0      0    10     0     0
# 2:  2      1      0      1    11     0    10
# 3:  3      0      1      1     0    10    12
# 4:  4      0      1      0     0     9     0

Or you can use reshape from base R, where NA has to be manually replaced: 或者,您可以从基数R使用reshape ,其中必须手动替换NA

test$type = 1
reshape(test, idvar = "ID", timevar = "Type", direction = "wide")

#   ID Val.A type.A Val.C type.C Val.B type.B
# 1  1    10      1    NA     NA    NA     NA
# 2  2    11      1    10      1    NA     NA
# 4  3    NA     NA    12      1    10      1
# 6  4    NA     NA    NA     NA     9      1

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM