Reputation: 13309
I'm new to R and stack overflow. I've searched online but couldn't find an answer to my question. I wanted to create a loop that extracts from a list and replaces the entry in the list.
(x<-list(1:5,NULL))
rpl<- function(x){
for(i in x){
if(x[[i]]==1)
x[[i]]<-25
}
}
Upvotes: 1
Views: 14894
Reputation: 11480
x<-list(1:5,NULL)
lapply(x, function(el) {
if(is.null(el)) el else {
ifelse(el %in% 1, 25, el)
}
})
#[[1]]
#[1] 25 2 3 4 5
#[[2]]
#NULL
use lapply
to work with and return lists.
It's better to use %in%
because ==
will fail on missing values.
Upvotes: 4