从R中的apply()函数返回多个值

Mat*_*ews 12 closures r

我想从apply()函数返回多个值并将它们放在R中的单独列中但我不断收到错误.我想要做的是这样的:

experiments$result1, experiments$result2, experiments$result3 <- apply(experiments, 1, 
function(row)
  #Some analysis here
  #return x, y, and z for column result1, result2, and result3
  x, y, z
)
Run Code Online (Sandbox Code Playgroud)

也许这是解决问题的错误方法.实验是一个包含多列数据的数据框.我想附加作为每行分析结果的列,但我不知道如何在没有循环的情况下做到这一点,这对于R来说不是惯用的.感谢提前帮助.

所以这里有一些更精确的代码.

experiments$result1, experiments$result2, experiments$result3 <- apply(experiments, 1, function(row)
  x <- row["startingTemp"]*2
  y <- row["startingTemp"]*3
  z <- row["startingTemp"]*4
  return (list(x, y, z))
)
Run Code Online (Sandbox Code Playgroud)

"startingTemp"字段是我的"实验"数据框中的一列.我收到的错误是'闭包'类型不是子集,而且找不到对象'z'.

Bac*_*lin 10

如果要返回的三个值可以放在向量中(即它们不是某种复杂类型,如统计测试或拟合模型的结果),只需返回向量apply并将其绑定到3xN矩阵.

experiments$result <- apply(experiments, 1, function(row){
  x <- row["startingTemp"]*2
  y <- row["startingTemp"]*3
  z <- row["startingTemp"]*4
  c(x, y, z)
})
experiments$result1 <- experiments$result[1,]
experiments$result2 <- experiments$result[2,]
experiments$result3 <- experiments$result[3,]
Run Code Online (Sandbox Code Playgroud)

如果您的三个返回值是复杂类型(或不是标量),则将它们作为列表返回(如Alan建议的那样)并用lapply/ 提取它们sapply.

experiment$result1 <- lapply(experiment$result, "[[", 1)
Run Code Online (Sandbox Code Playgroud)