【问题标题】:Reshaping data - is this an operation for tidyr::spread?重塑数据 - 这是 tidyr::spread 的操作吗?
【发布时间】:2015-08-01 16:29:45
【问题描述】:

我正在尝试重塑数据框,使列中的每个唯一值都成为二进制列。

我收到的数据如下所示:

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,1

spread(df,id,feature) 失败,因为 id 重复。

我想重塑数据以促进建模 - 我试图根据特征的存在与否来预测价值。

【问题讨论】:

  • reshape2 包的 dcast(df, id + value ~ ..., length) 运行良好。但这个问题很可能是重复的。

标签: r tidyr


【解决方案1】:

不过,有一种方法可以使用 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 1

【讨论】:

  • 您可以在spread 中使用fill 参数,即mutate(df, v=1) %&gt;% spread(feature, v, fill=0)
【解决方案2】:

正如我之前的评论: 您必须使用reshape2 包的dcast,因为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

【讨论】:

    猜你喜欢
    • 2019-11-15
    • 2016-01-22
    • 2016-05-24
    • 1970-01-01
    • 2016-09-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多