how do I get individual elements of functions in a list and put them in a matrix in R? [closed]

北城以北 提交于 2021-02-08 10:40:28

问题


Edit: Included a sample result

I created functions like so:

Ex1 = function(a,b,c) 1 * a + 2 * b + 3 * c + 4
Ex2 = function(a,b,c)
Ex3 = function(a,b,c)
etc..

and put them in a list:

exList = list(Ex1,Ex2,Ex3,etc.)

now I have to use a function to get the individual elements ([a,b,c] and the numbers (separately))

I'm having trouble there for the most part, having tried substring and split to no avail (or I'm just not using it properly), since I do know how to create a matrix.

An example of the result would be:

   a  b  c RHS
1  1  2  3  4
2  5  6  7  8
3  9 10 11  12

But long story short, I need to create an Augmented Coefficient Matrix.

Any help would be great. Thanks!


回答1:


You can extract the numbers like this:

Ex1 <- function(a,b,c) 1 * a + 2 * b + 3 * c + 4


foo <- function(x) {
  if(length(x) > 1) {
    res <- lapply(x, foo)
  } else {
      res <- if(is.numeric(x)) x else NA
  }
  na.omit(unlist(res))
}

foo(body(Ex1))
#[1] 1 2 3 4

However, I strongly encourage you to change your whole approach. It could be something like this:

coefs <- list(c1 = c(1, 2, 3, 4), c2 = c(5, 6, 7, 8))
callerFun <- function(a, b, c, coefs) c(cbind(a, b, c, 1) %*% coefs)

#example use
a <- 1:2
b <- 3:4
c <- 5:6

lapply(coefs, callerFun, a = a, b = b, c = c)
#$c1
#[1] 26 32
#
#$c2
#[1] 66 84


来源:https://stackoverflow.com/questions/65003838/how-do-i-get-individual-elements-of-functions-in-a-list-and-put-them-in-a-matrix

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!