如何将列表的每个元素作为参数分配给 R 中循环中的函数? [英] how to assign each element of a list as arguments to a function in a loop in R?

查看:25
本文介绍了如何将列表的每个元素作为参数分配给 R 中循环中的函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 R 的新手.我想根据因子列(例如 A 列和B).首先,我希望通过对 A 列和 B 列进行分组来获得结果,然后单独对 A 和 B 进行相同的操作.我写了一个看起来像下面的代码.我有一个我想要测试的因子组合列表 (groupList),然后对于循环的每次迭代,我将该列表的一个元素作为参数提供给by".但是,正如您肯定看到的,它不起作用.R 不会将列表的元素识别为函数by"的参数.关于如何使这项工作的任何想法?欢迎并感谢任何指点或建议.

I'm new to R. I'd like to get a number of statistics on the numeric columns (say, column C) of a data frame (dt) based on the combination of factor columns (say, columns A and B). First, I want the results by grouping both columns A and B, and then the same operations by A alone and by B alone. I've written a code that looks like the one below. I have a list of the factor combinations that I'd like to test (groupList) and then for each iteration of the loop I feed an element of that list as the argument to "by". However, as surely you can see, it doesn't work. R doesn't recognize the elements of the list as arguments to the function "by". Any ideas on how to make this work? Any pointer or suggestion is welcome and appreciated.

groupList <- list(".(A, B)", "A", "B")

for(i in 1:length(groupList)){
  output <- dt[,list(mean=mean(C),
                     sd=sd(C),
                     min=min(C),
                     median=median(C),
                     max=max(C)),
               by = groupList[i]]

  Here insert code to save each output
}

推荐答案

您的 groupList 可以重组为字符向量列表.然后您可以使用 lapply 或现有的 for 循环和添加的 eval() 来解释 by=正确输入:

Your groupList can be restructured as a list of character vectors. Then you can either use lapply or the existing for loop with an added eval() to interpret the by= input properly:

set.seed(1)
dt <- data.table(A=rep(1:2,each=5), B=rep(1:5,each=2), C=1:10)

groupList <- list(c("A", "B"), c("A"), c("B"))

lapply(
  groupList,
  function(x) {
    dt[, .(mean=mean(C), sd=sd(C)), by=x]
  }
)

out <- vector("list", 3)
for(i in 1:length(groupList)){
  out[[i]] <- dt[, .(mean=mean(C), sd=sd(C)), by=eval(groupList[[i]]) ]
}

str(out)
#List of 3
# $ :Classes ‘data.table’ and 'data.frame':      6 obs. of  4 variables:
#  ..$ A   : int [1:6] 1 1 1 2 2 2
#  ..$ B   : int [1:6] 1 2 3 3 4 5
#  ..$ mean: num [1:6] 1.5 3.5 5 6 7.5 9.5
#  ..$ sd  : num [1:6] 0.707 0.707 NA NA 0.707 ...
#  ..- attr(*, ".internal.selfref")=<externalptr> 
# $ :Classes ‘data.table’ and 'data.frame':      2 obs. of  3 variables:
#  ..$ A   : int [1:2] 1 2
#  ..$ mean: num [1:2] 3 8
#  ..$ sd  : num [1:2] 1.58 1.58
#  ..- attr(*, ".internal.selfref")=<externalptr> 
# $ :Classes ‘data.table’ and 'data.frame':      5 obs. of  3 variables:
#  ..$ B   : int [1:5] 1 2 3 4 5
#  ..$ mean: num [1:5] 1.5 3.5 5.5 7.5 9.5
#  ..$ sd  : num [1:5] 0.707 0.707 0.707 0.707 0.707

这篇关于如何将列表的每个元素作为参数分配给 R 中循环中的函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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