dcast 然后连接转换后的变量

dcast then concatenate transformed variables

我有一个包含两个变量 x 和 y 的数据框 ("df"):

a <- c(1:2000)
b <- c(1:4000)
c <- 5000

df <- data.frame(x = sample(a, c, replace = TRUE),
                 y = as.character(sample(b, c, replace = TRUE)))
df <- df[order(df$x), ]

head(df, 10)
     x    y
881  1 2919
4425 1 2000
2478 2 3375
4808 2 3928
4871 2 3351
4889 2 1634
1242 3 3957
1378 3 3356
3029 3 2625
3657 4  646

我现在想做的是将数据帧缩减为仅包含不同的 x 变量(例如,一个“1”、一个“2”、一个“3”等)并有一个新字段连接每个不同的 x 的 y 值,用逗号分隔。最终结果如下所示:

head(df3)
  x               multi_ys
1 1             2000, 2919
2 2 1634, 3351, 3375, 3928
3 3       2625, 3356, 3957
4 4              1092, 646
5 5   113, 2430, 3187, 932
6 7                   2349

我现在有一个可行的解决方案,但我认为它比必要的更麻烦。我的当前状态解决方案如下,对于 5,000 行的 "df" 数据框,创建 "df3".

大约需要 12 秒
library(reshape2)

#creates a duplicate field of y, to dcast in the 'multi_y' function below
df$y2 <- df$y

#creates a new dataframe with unique x values
df2 <- df[which(!duplicated(df$x)), ]


multi_y <- function(x) {
  c3.i <- df2[x, 1]
  c3.j <- df[df$x == c3.i, ]
  c3.k <- dcast(c3.j, x ~ y, value.var = "y2")
  cols <- colnames(c3.k)

  #if there are more than two columns in this loop's data frame, then concatenate all columns except the first
  if(ncol(c3.k) > 2) {
    c3.k$cycles <- apply( c3.k[ , cols[-1]] , 1 , paste , collapse = ", " )
  } else {
    c3.k$cycles <- c3.k[, 2]
  }

  c3.l <- cbind(data.frame(c3.k[, 1]), data.frame(c3.k[, ncol(c3.k)]))
  colnames(c3.l) <- c("x", "multi_ys")
  print(c3.l)
}

t <- (1:nrow(df2))
system.time(df3 <- do.call("rbind", lapply(t, function(x) multi_y(x))))

我的实际数据框超过 80,000 行,我必须在我的程序中 运行 这种类型的函数 4 次不同的时间。

我很感激你能提供任何帮助我加快这个过程的建议。

怎么样,

df1 <- aggregate(y~x, df, paste, collapse = ',')
head(df1)
#  x                                   y
#1 1                                 542
#2 2                      3813,1220,1666
#3 3 1713,35,643,3957,872,2235,3015,3051
#4 4                      2037,1371,1180
#5 5                            2724,905
#6 6                            293,3248