# Removing a specific number from all lists in a column of lists in R

• A+
Category：Languages

I have a column in a dataframe that stores lists. Here is an example below:

``           col 1   9, 8, 3, 7 2   8, 8, 8, 5 3   1, 8, 10, 4 4   3, 6, 1, 6 5   9, 9, 10, 4 6   8, 8, 9, 2 7   6, 10, 4, 7 8   6, 1, 5, 9 9   4, 7, 5, 10 10  7, 9, 2, 5 ``

This is the code I used to generate the above example:

``example <- data.frame(matrix(NA_real_, nrow=10, ncol=1)) colnames(example) <- "col" x <- list(c(1,2,3,4)) for(y in 1:10) {   example\$col[y] <- list(c(c(sample(1:10,1)),c(sample(1:10,1)),c(sample(1:10,1)),c(sample(1:10,1)))) } ``

I want to remove all occurrences of the number 9 from all of these lists, in this column of my data frame, to get something like this:

``           col 1   8, 3, 7 2   8, 8, 8, 5 3   1, 8, 10, 4 4   3, 6, 1, 6 5   10, 4 6   8, 8, 2 7   6, 10, 4, 7 8   6, 1, 5 9   4, 7, 5, 10 10  7, 2, 5 ``

I'm currently trying to do something like this to go about this problem:

``lapply(example, `[<-`, , "col", function(x) ifelse(x==1, NULL, 1)) ``

I keep getting the following error:

``Error in lapply(example, `[<-`, , "col", function(x) ifelse(x == 1, NULL,  :    incorrect number of subscripts on matrix ``

How can I resolve this error and fix my problem? Are there any other ways to solve this?

Base R:

``> example            col 1  10, 9, 3, 9 2   4, 7, 9, 3 3   5, 9, 5, 3 4   5, 4, 5, 4 5  10, 6, 2, 6 6   4, 7, 5, 9 7   1, 7, 1, 6 8  4, 9, 2, 10 9   3, 9, 3, 2 10  1, 6, 1, 4  example\$col <- lapply(example\$col, function(x){   x[x != 9] })  > example            col 1        10, 3 2      4, 7, 3 3      5, 5, 3 4   5, 4, 5, 4 5  10, 6, 2, 6 6      4, 7, 5 7   1, 7, 1, 6 8     4, 2, 10 9      3, 3, 2 10  1, 6, 1, 4 ``