我试图重塑一个数据框架,以便列中的每个唯一值都变成一个二进制列。
我得到的数据如下:
df <- data.frame(id = c(1,1,2),
value = c(200,200,1000),
feature = c("A","B","C"))
print(df)
##id,value,feature
##1,200,A
##1,200,B
##2,1000,C我试着把它重塑成这样:
##trying to get here
##id,value,A,B,C
##1,200,1,1,0
##2,1000,0,0,1spread(df,id,feature)失败,因为ids重复。
我想重塑数据,以便于建模--我正试图从特性的存在或缺失中预测价值。
发布于 2015-08-01 16:35:08
正如我前面的评论:您必须使用reshape2包的reshape2,因为spread对于处理和/或符合整洁数据原则的数据很有效。你的“传播”有点不同(而且很复杂)。当然,除非您将spread与其他函数结合使用。
library(reshape2)
dcast(df, id + value ~ ..., length)
id value A B C
1 1 200 1 1 0
2 2 1000 0 0 1发布于 2015-08-01 16:36:36
不过,有一种方法可以使用tidyr::spread,使用始终等于1的转换变量。
library(dplyr)
library(tidyr)
mutate(df,v=1) %>%
spread(feature,v,fill=0)
id value A B C
1 1 200 1 1 0
2 2 1000 0 0 1https://stackoverflow.com/questions/31763757
复制相似问题