【问题标题】:Combining variable number of fields across data.frame, using mapply使用 mapply 跨 data.frame 组合可变数量的字段
【发布时间】:2015-01-19 02:57:32
【问题描述】:

我有包含字符列的数据框,比如说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 将适用于 data.frame 列,而不是行。所以我想你需要像mapply(xyp, data.frame(t(tdf)), tcol) 这样的东西。无论如何,这并不完美。

标签: r mapply


【解决方案1】:

怎么样

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

在这里,我们使用split() 将 data.frame 分割成行列表,而不是 data.frame 通常的情况下的列列表。

【讨论】:

  • split(tdf,rownames(tdf)) - 它们在data.frame中必须是唯一的,所以它会分割每一行。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-09-24
  • 1970-01-01
  • 2022-08-04
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多