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

时间:2015-01-19 02:57:32

标签: r 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

我想我理解错误,但不知道我能做些什么来解决这个问题。有什么建议吗?

1 个答案:

答案 0 :(得分:1)

怎么样

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

在这里,我们使用split()将data.frame切片为行列表而不是列表列表,通常是data.frame的情况。