Replace numeric(0) with NAs in all lists in a column of lists in r

The name of the pictureThe name of the pictureThe name of the pictureClash Royale CLAN TAG#URR8PPP



Replace numeric(0) with NAs in all lists in a column of lists in r



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


col
1 9
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:


set.seed(123)
example <- data.frame(matrix(NA_real_, nrow=10, ncol=1))
colnames(example) <- "col"
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))))


example$col[1] <- list(c(9))



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 NA
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



instead of this, which I'm currently getting with example$col <- lapply(example$col, function(x) x[x != 9] )


example$col <- lapply(example$col, function(x) x[x != 9] )


col
1 numeric(0)
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



How can I replace the numeric(0) with NA_real_ and still be able to remove all the 9s?


numeric(0)


NA_real_




2 Answers
2



Modify your lapply statement like so


lapply


lapply(example$col, function(x) y <- x[x != 9]; if(length(y) < 1) y <- NA ; y )



As own function - makes it easier to modify in the future


remove_num <- function(vec, num)
x <- vec[vec != num]
if (length(x) < 1) x <- NA
x


lapply(example$col, remove_num, 9)



You could do both, remove the 9s and change single 9s to NA_real_, in one step with an if statement.


NA_real_


if


example$col <- lapply(example$col, function(x)
if(length(x) == 1L && x == 9) NA_real_ else x[x != 9]
)

example
# col
# 1 NA
# 2 10, 1, 6
# 3 6, 5, 10, 5
# 4 7, 6, 2
# 5 3, 1, 4, 10
# 6 7, 7, 10
# 7 7, 8, 6, 6
# 8 3, 2, 10, 10
# 9 7, 8, 1, 5
# 10 8, 3, 4, 3






By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Popular posts from this blog

Firebase Auth - with Email and Password - Check user already registered

Dynamically update html content plain JS

How to determine optimal route across keyboard