使用 mapply 在 data.frame 中合并可变数量的字段

Combining variable number of fields across data.frame, using mapply

我有一个包含字符列的数据框,比方说 tdf <- data.frame(words=letters[1:4], words2=letters[5:8], word3=letters[9:12])

我还有一个相应的向量,说明用于组合每行中单词的最后一列编号,比方说 tcol <- c(3, 1, 1, 2)

因此,例如对于第四行,输出应为 "d h"

我写了一个可以处理每一行合并的函数

xyp <- function(x, y) do.call(paste, as.list(x[1:y]))

for 循环中按预期工作

> y <- character(0)
> for (x in 1:nrow(tdf)) y <- c(y, xyp(tdf[x, ], tcol[x]))
> y
[1] "a e i" "b"     "c"     "d h"  

我想在不使用 for 循环的情况下跨数据框应用该函数,但上面的函数似乎不适用于此目的。

> mapply(xyp, tdf, tcol)
  words  words2   word3    <NA> 
"a b c"     "e"     "i"   "a b" 
Warning message:
In mapply(xyp, tdf, tcol) :
  longer argument not a multiple of length of shorter

我想我明白了这个错误,但我不确定我能做些什么来解决这个问题。有什么建议吗?

怎么样

mapply(function(x, i) paste(x[1:i], collapse=" "), 
    split(as.matrix(tdf),row(tdf)), 
    tcol)

这里我们使用 split() 将 data.frame 分割成行列表,而不是像 data.frame.

通常情况下的列列表