从R中的apply()函数返回多个值 [英] Return multiple values from apply() function in R

查看:48
本文介绍了从R中的apply()函数返回多个值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am wanting to return multiple values from the apply() function and place them in separate columns in R but I keep getting errors. What I am trying to do is this:

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
)

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

Maybe this is the wrong approach to the problem. Experiments is a data frame with several columns of data. I am wanting to append columns which are the result of the analysis for each row but I don't know how to do that without loops which is not idiomatic for R. Thanks for the help ahead of time.

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

So here is some more exact code.

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))
)

"startingTemp"字段是我的"experiments"数据框中的列之一.我收到错误消息,提示"closure"类型不可子集化,找不到对象"z".

the "startingTemp" field is one of the columns in my "experiments" data frame. I'm getting errors that the type 'closure' is not subsettable and object 'z' not found.

推荐答案

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

If the three values you want to return can be put in a vector (i.e. they are not of some complicated type like the results of a statistical test or a fitted model), just return the vector and apply will bind it to an 3xN matrix.

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,]

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

If your three return values are of a complicated type (or not scalars) return them as a list (like Alan suggested) and extract them with lapply/sapply.

experiment$result1 <- lapply(experiment$result, "[[", 1)

这篇关于从R中的apply()函数返回多个值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆