score324
score324

Reputation: 717

How to check if a list contains a certain element in R

I have the following list

A = list(c(1,2,3,4), c(5,6,7,8), c(4,6,2,3,1), c(6,2,1,7,12, 15, 16, 10))
A
[[1]]
[1] 1 2 3 4

[[2]]
[1] 5 6 7 8

[[3]]
[1] 4 6 2 3 1

[[4]]
[1]  6  2  1  7 12 15 16 10

I want to check if the element 2 is present each list or not. If it exists, then I need to assign 1 to that corresponding list.

Thank you in advance.

Upvotes: 4

Views: 7481

Answers (3)

paoloeusebi
paoloeusebi

Reputation: 1086

Here is a simple version with replacement!

lapply(A, function(x) ifelse(x==2,1,x))

Upvotes: 2

akrun
akrun

Reputation: 887991

Here is an option with tidyverse

library(tidyverse)
map_lgl(A, `%in%`, x = 2) %>% 
    as.integer
#[1] 1 0 1 1

Upvotes: 2

Julius Vainora
Julius Vainora

Reputation: 48251

@jasbner's comment can be further refined to

1 * sapply(A, `%in%`, x = 2)
# [1] 1 0 1 1

In this case sapply returns a logical vector, and then multiplication by 1 coerces TRUE to 1 and FALSE to 0. Also, as the syntax is x %in% table, we may avoid defining an anonymous function function(x) 2 %in% x and instead write as above. Lastly, using sapply rather than lapply returns a vector rather than a list, which seems to be what you are after.

Upvotes: 5

Related Questions