Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/three.js/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
从R中的apply()函数返回多个值_R_Closures - Fatal编程技术网

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

从R中的apply()函数返回多个值,r,closures,R,Closures,我想从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 )

我想从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
)
experiments$result1、experiments$result2、experiments$result3Try
return(列表(x=x,y=y,z=z))
。对于每个实验,返回一个包含3个值的列表

编辑


函数为每个实验返回一个列表

results <- apply(exp,1,function(x) return(list(x=x,y=x*2,z=x*3))) #results is a list of lists`
experiment$res1 <- unlist(results)[attr(unlist(results),"names")=="x"]
experiment$res2 <- unlist(results)[attr(unlist(results),"names")=="y"]
experiment$res3 <- unlist(results)[attr(unlist(results),"names")=="z"]

results如果要返回的三个值可以放在一个向量中(即它们不是统计测试或拟合模型的结果那样的复杂类型),只需返回向量,然后
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,]

我在问题中补充了一些信息。我尝试了你的建议,但出现了错误。函数为每个实验返回一个列表。
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,]
experiment$result1 <- lapply(experiment$result, "[[", 1)