如何应用于矩阵列表中第j个矩阵的每个第i列

时间:2018-06-13 04:36:36

标签: r list matrix lapply sapply

我正在尝试编写一些对列表中的矩阵进行操作的函数,以便针对列表中的每个矩阵对每个矩阵内的一组列执行特定操作。该代码处理的项目涉及的是不可挖掘的数据,因此我无法共享确切的代码和数据。但是,这里有一些代码可以重现我所遇到的挣扎的例子。任何人都可以启发我如何使用* apply在第j个矩阵函数中完成第i列?

 ### This will generate a list of data frames so there is an reproducible example.
list = lapply(seq(1:10), function(x) dplyr::sample_n(iris[,1:4], size=30))

### List the number of columns per matrix for ease
n_i = 4

### If I manually set the list index the function works fine (for that list). Let's suppose I want the residuals for all variables being predicted by Sepal.Width
get.residuals = function(i) {
 residuals(lm(y ~ ., data=cbind.data.frame(y=list[[5]][,i], list[[5]][,2])))
}

### This gives the residuals for each variable given all other variables. This doesn't make sense here of course.
sapply(c(1,3,4), function(i) get.residuals(i))

### Looks perfect. The output is the residuals for three variables specified in c(1,3,4) being predicted by Sepa.Width

### Now I want to extract the residuals for every column i in each matrix j in the list. I won't show them  all here, but I've tried probably 50 different variations of the functions and uses of lapply,sapply,apply,and for loops and just can't seem to get it to do what I'd like. 

### As an example of an attempt that thows the error "Error in terms.formula(formula, data = data) : '.' in formula and no 'data' argument

get.residuals = function(i,j) {
 residuals(lm(y ~ ., data=cbind.data.frame(y=list[[j]][,i], list[[j]][,2])))
}

lapply(list, function(j) get.residuals(i))

0 个答案:

没有答案