在组内 reshape 数据 - 一行中的组

标签 r dplyr reshape2

<分区>

这是我的输入数据:

 DeviceID   ContentID   Use
 D1 C1  0.678491346
 D1 C2  0.302147374
 D2 C1  0.695790066
 D2 C2  0.645849165
 D3 C1  0.83503997
 D3 C2  0.3622916

预期输出:

DeviceID    ContentID_1 Use_1   ContentID_2 Use_2
D1  C1  0.678491346 C2  0.302147374
D2  C1  0.695790066 C2  0.645849165
D3  C1  0.83503997  C2  0.3622916

我尝试使用 reshape2 reshape 它,但无法以所需的格式获得它。

我试过了:

 df %>% 
   group_by(DeviceID) %>% 
   mutate(rn = paste0("Content",row_number())) %>% 
   spread(rn, Use)

dcast(df,
      DeviceID~ContentID,
      value.var ="Use")

任何帮助将不胜感激!

最佳答案

发布我的解决方案:

library(splitstackshape)
library(tidyverse)

df %>%
  group_by(DeviceId) %>%
  summarise_all(function(x) paste0(x, collapse = "_")) %>%
  cSplit(names(.)[-1], '_')

在评论中包含@AntoniosK 的建议。

关于在组内 reshape 数据 - 一行中的组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48517648/

相关文章:

r - 在 R 中结合向量化和递归?

r - 如何提取特定行并将其设为R中的列?

r - 如何将 tibble 中的行乘以另一个 tibble 中的另一个对应行

r - 为什么在 R 中的 data.table 中使用 "could not find function "函数时会收到此错误消息 "melt"模式

r - 在 R 中使用 dcast 将数据帧从长格式转换为宽格式不起作用

r - 实三次多项式的最快数值解?

r - 如何绘制线性回归到双对数 R 图?

r - 融化多组 measure.vars

r - "Set working directory to source file location"的命令

r - DPLYR 过滤多个组,每个组都有自己的标准