USER_1
USER_1

Reputation: 2469

lapply'ing a for loop returns NULL

I have a simple list

list1<-data.frame(col1=c("text;aaa","text", "text;aaa","text"), col2=1:4)
list2<- data.frame(col1=c("text;aaa","text", "text;aaa","text", "text", "text"), col2=1:6)
mylist<-list(list1,list2)

I now want to sub all text after ; with a for loop, like this

list.2 <- lapply(mylist, function(x){
  for(i in 1:nrow(x)){
    if(grepl(";",x[i,1]) == T){
      x[i,1] <- gsub(";.*", "", x[i,1])
    } else x[i,1] <- x[i,1]
  }
}  )

But the output is NULL

list.2
[[1]]
NULL

[[2]]
NULL

What am I missing here?

Upvotes: 1

Views: 98

Answers (1)

LyzandeR
LyzandeR

Reputation: 37879

You need to return x in the function within lapply otherwise nothing will get returned:

lapply(mylist, function(x){
  for(i in 1:nrow(x)){
    if(grepl(";",x[i,1])){
      x[i,1] <- gsub(";.*", "", x[i,1])
    } else x[i,1] <- x[i,1]
  }
  #return the x you modified previously
  x
})

Output:

[[1]]
  col1 col2
1 text    1
2 text    2
3 text    3
4 text    4

[[2]]
  col1 col2
1 text    1
2 text    2
3 text    3
4 text    4
5 text    5
6 text    6

Also, as a side note, you do not need grepl(";",x[i,1]) == T but only grepl(";",x[i,1]) since grepl returns TRUE or FALSE anyway (so you do not need to test for TRUE==TRUE).

Upvotes: 1

Related Questions