Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to delete a slot of an element in a list in R with lappy

Tags:

r

lapply

So i have a long list of objects that each have a slot that i want to delete. Specifically they are storing the data in a duplicate manner. But the reason why shouldn't matter.

My main question regards what is "proper" way of doing this. So here is the set up:

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 look objects). I want to delete the useless slot. why, because it is useless to me.

I can do with a loop:

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

But why doesn't the lapply() version work. So guess the question is what do I not get about lapply.

lapply(SampleList, function(x){print(x$useless) })
SampleList<- lapply(SampleList, function(x){x$useless <- NULL }) #NO WORK
like image 483
jdennison Avatar asked Aug 08 '12 17:08

jdennison


1 Answers

Your function inside the lapply isn't returning anything so it defaults to returning the result of your assignment. You need to return the modified object for your version to work

SampleList <- lapply(SampleList, function(x){x$useless <- NULL; x})
like image 136
Dason Avatar answered Sep 21 '22 23:09

Dason