简体   繁体   English

将列表对象转换为可用的矩阵名称(R)

[英]Convert A List Object into a Useable Matrix Name (R)

I want to be able to use a loop to perform the same funtion on a group of data sets without having to recall the name of all of the data sets individually. 我希望能够使用循环对一组数据集执行相同的功能,而不必分别调用所有数据集的名称。 For example, say I have the following matricies: 例如,说我有以下矩阵:

a<-matrix(1:5,nrow=5,ncol=2)
b<-matrix(6:10,nrow=5,ncol=2)
c<-matrix(11:15,nrow=5,ncol=2)

I define a vector of set names: 我定义了一个集合名称的向量:

SetNames<- c("a","b","c")

Then I want to sum the second column of all of the matricies without having to call each matrix name. 然后,我想对所有矩阵的第二列求和,而不必调用每个矩阵名称。 Basically, I would like to be able to call SetNames[1] , have the program return 'a' as USEABLE text which can be used to call apply(a[2],2,sum) . 基本上,我希望能够调用SetNames[1] ,让程序以可用文本返回“ a”,该文本可用于调用apply(a[2],2,sum)

If apply(SetNames[1][2],2,sum) worked, that would be the basic syntax I was looking for, however I would replace the 1 with a variable I can increase in a loop. 如果apply(SetNames[1][2],2,sum)起作用,那将是我一直在寻找的基本语法,但是我将1替换为可以在循环中增加的变量。

sapply can do that. sapply可以做到。

sapply(SetNames, function(z) {
  dfz <- get(z)
  sum(dfz[,2])
})
#  a  b  c 
# 15 40 65 

Notice that get() is used here to dynamically access a variable. 请注意,此处使用get()动态访问变量。

a less compact way of writing this would be 一种不太紧凑的书写方式是

sumRowTwo <- function(z) {
  dfz <- get(z)
  sum(dfz[,2])
}
sapply(SetNames, sumRowTwo)

and now you can play around with sumRowTwo and see what eg 现在您可以使用sumRowTwo来看看

sumRowTwo("a")

returns 退货

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM