Home > OS >  Using lapply to nested list
Using lapply to nested list

Time:03-10

I have a next structure data frame qw[[i]], i = 19 (nested list). For example:

dput(qw[[19]])
list(c(87.6755555555556, 36, 117.277222222222, 64.7858333333333
), c(46.44, 19.4966666666667, 207.101666666667, 92.5783333333333)
...

And I don't know how to use lapply (X, FUN = norm), that calculate norm for each block:

list(c(87.6755555555556, 36, 117.277222222222, 64.7858333333333)
qnw <- lapply(matrix(unlist(qw)), FUN = norm)

after I get the same error:

Error in FUN(X[[i]], ...) : 'A' must be a numeric matrix

How fix it?

CodePudding user response:

It seems like a nested list of vectors. We may use recursive apply (rapply)

rapply(qw, f = \(x) norm(matrix(x)))

Or use a nested sapply/lapply

as.vector(sapply(qw, \(x) sapply(x, \(y) norm(matrix(y)))))
  •  Tags:  
  • r
  • Related