Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Using lapply to nested list

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

How fix it?

>Solution :

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)))))
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading