[英]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)
因此,例如对于第四行,输出应为"dh"
。
我写了一个可以处理每一行合并的函数
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的情况将列切片为列。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.