I have a list similar to the following:
> x <- list(
j = "first",
k = "second",
l = "third",
m = c("first", "second"),
n = c("first", "second", "third"),
o = c("first", "third"),
p = c("second", "third"),
q = "first",
r = "third")
I need to create index of the string components based on their value. I can easily do this with which
for components containing elements of single strings:
> which(x == "third")
l r
3 9
Or even for multiple components that contain elements of single strings:
> which(x == "first" | x == "second" | x == "third")
j k l q r
1 2 3 8 9
The returned value shows me the number of the components in the list and its name. However, sometimes I would need to obtain an index of components that contain character vectors that have more than one element such as m
(c("first", "second")
) or n
(c("first", "second", "third")
). That is, the length of the character vector in the components would be larger than 1. I thought the following would work:
which(x == c("first", "second"))
I was wrong, the output was:
j k
1 2
Warning message:
In x == c("first", "second") :
longer object length is not a multiple of shorter object length
It is the same when I try with more than one condition:
> which(x == "first" | x == c("first", "second"))
j k q
1 2 8
Warning message:
In x == c("first", "second") :
longer object length is not a multiple of shorter object length
The desired output from which(x == c("first", "second"))
is:
m
4
The desired output from which(x == "first" | x == c("first", "second"))
is:
j m q
1 4 8
How this could be done? Not necessary to use which
, thou...