【问题标题】:Transpose rows to columns with multiple categories dplyr将行转置为具有多个类别的列 dplyr
【发布时间】:2017-10-09 14:57:00
【问题描述】:

我想使用tidyr 的扩展函数将行和多列中具有多个 id 的数据框转换为具有一行的 df,其中我们有针对 id 和类别的所有组合的指示列。如果dplyrtidyr 不是最合适的,请打开其他类似传播的功能。

在下面的脚本中,我只能指定 1 列作为值对。我想将 cat1 和 cat2 作为值列。另外,我希望字段名称为“sentid1_cat1、sentid1_cat2”等。

test.df <- data.frame(sentid = 1:3, 
                      cat1 = c(1,0,0), 
                      cat2 = c(0,1,0))

test.df %>%
    spread(key = sentid, value = cat1, sep = '_')

编辑

期望的输出:

output.df <- data.frame(sentid1_cat1 = 1,
                        sentid1_cat2 = 0,
                        sentid2_cat1 = 0,
                        sentid2_cat2 = 1,
                        sentid3_cat1 = 0,
                        sentid3_cat2 = 0)

【问题讨论】:

  • 我有点不确定你在问什么。您介意包含所需结果的输出 df 吗?
  • 也许this post 会有所帮助。如果您显示所需的输出,将会很有帮助。
  • 我的回答能解决你的问题吗?

标签: r dplyr tidyr spread


【解决方案1】:

dplyr + tidyr 的解决方案:

library(dplyr)
library(tidyr)

test.df %>%
  gather(variable, value, -sentid) %>%
  unite(variable, sentid, variable) %>%
  mutate(variable = paste0("sentid", variable)) %>%
  spread(variable, value) 

结果:

  sentid1_cat1 sentid1_cat2 sentid2_cat1 sentid2_cat2 sentid3_cat1 sentid3_cat2
1            1            0            0            1            0            0

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-23
    • 1970-01-01
    相关资源
    最近更新 更多