Reputation: 312
Why does this example work:
which(letters %in% c('j', 'e', 'f', 'f', 'r', 'e', 'y'))
However; this one does not?
name <- c(strsplit("jeffrey", ""))
which(letters %in% name)
Isn't this the exact same thing since in both instance the second argument in the which function is a vector?
Upvotes: 2
Views: 38
Reputation: 887691
The issue is that the strsplit
is still a list
of length
1 with the first element a vector
strsplit("jeffrey", "")
#[[1]]
#[1] "j" "e" "f" "f" "r" "e" "y"
Wrapping with c
is not going to change the scenario as by default recursive = FALSE
.
c(strsplit("jeffrey", ""))
#[[1]]
#[1] "j" "e" "f" "f" "r" "e" "y"
Changing the recursive = TRUE
will make it possible to convert the list
to a vector
c(strsplit("jeffrey", ""), recursive = TRUE)
#[1] "j" "e" "f" "f" "r" "e" "y"
If we use unlist
(as in @JohnyCrunch's solution), it unlists the list
because by default recursive = TRUE
and convert to vector
. In our case, another approach would be to extract the list
element with [[
(as it is only a list
of length
1.
name <- strsplit("jeffrey", "")[[1]]
which(letters %in% name)
#[1] 5 6 10 18 25
Upvotes: 4
Reputation: 4480
If you run class(name)
you will note that it is a list. Use unlist()
to solve the problem:
name <- unlist(strsplit("jeffrey", ""))
which(letters %in% name)
Best!
Upvotes: 3