分布在 R 中的一列

Spreading over a column in R

假设我有这样一个数据框:

data.frame(x = c(1,1,1,3,3,3),y = c(12,32,43,16,32,65))

我想将其转换成这样的数据框:

data.frame(x = c(1, 3), y_1 =  c(12,16), y_2 =c(32, 32),y_3= c(43, 65))

基本上为每个唯一的 x 值传播 y 值。我试过使用 tidyr 来做到这一点,但不太清楚它是如何工作的。有什么想法吗?

谢谢。

这是一个 data.table 解决方案:

library(data.table)

dat = as.data.table(df) # or setDT to convert in place

dat[, obs := paste0('y_', 1:.N), by=x]
dcast(dat, x ~ obs, value.var="y")

#   x y_1 y_2 y_3
#1: 1  12  32  43
#2: 3  16  32  65

即使所有 x 的行数都不相同,这仍然有效。

我们可以使用aggregate,然后splitstackshape包中的cSplit强制到数据框,

library(splitstackshape)
df1 <- aggregate(y ~ x, df, paste, collapse = ',')
df1 <- cSplit(df1, 'y', ',', direction = 'wide')
#   x y_1 y_2 y_3
#1: 1  12  32  43
#2: 3  16  32  65

Sotos 使用 aggregate 给出的答案特别优雅,但以下使用 reshape 的方法也可能具有指导意义:

df <- data.frame(x = c(1,1,1,3,3,3),y = c(12,32,43,16,32,65))
df[,"time"] <- rep(1:3, 2)
wide_df <- reshape(df, direction="wide", timevar="time", idvar="x")

一个选项 dplyr/tidyr

library(dplyr)
library(tidyr)
df1 %>% 
    group_by(x) %>% 
    mutate(n = paste("y", row_number(), sep="_")) %>%
    spread(n,y)
#     x   y_1   y_2   y_3
#   (dbl) (dbl) (dbl) (dbl)
#1     1    12    32    43
#2     3    16    32    65