How to remove item slot in list in R with lappy

So, I have a long list of objects, each of which has a slot that I want to delete. In particular, they store data in duplicate. But the reason does not matter.

My main question is what is the β€œright” way to do this. So here is the setup:

q <- list() q$useless <- rnorm(100) q$useful <- rnorm(100) SampleList <- list(q,q,q) 

So, I have a list of identical objects (or at least identical view objects). I want to remove a useless slot. why, because it is useless to me.

I can do with the loop:

 for (i in 1:length(SampleList)){ SampleList[[i]]$useless <- NULL } 

But why is the lapply () version not working. So guess, the question is what I won’t get about myself.

 lapply(SampleList, function(x){print(x$useless) }) SampleList<- lapply(SampleList, function(x){x$useless <- NULL }) #NO WORK 
+4
source share
2 answers

Your function inside lapply does not return anything, so the result of your assignment is returned by default. You need to return the modified object for your version to work.

 SampleList <- lapply(SampleList, function(x){x$useless <- NULL; x}) 
+6
source

Try this simple version of lapply

 SampleList <- lapply(1:3, function(x, i) x[[i]]$useful, x=SampleList) 

or even this one, which is simpler than the previous one

 lapply(SampleList, function(x) x$useful) 

Both teams select only useful elements. Instead of replacing the useless with NULL this call simply select those that are useful .

+1
source

All Articles