Reputation: 575
I am a newbie to R. I have a list t1
in R which looks like
[[1]]
[[1]][[1]]
[1] "a" "control"
[[2]]
[[2]][[1]]
[1] "a" "disease1"
[[3]]
[[3]][[1]]
[1] "a" "disease2"
[[4]]
[[4]][[1]]
[1] "b" "control"
[[5]]
[[5]][[1]]
[1] "b" "disease1"
[[6]]
[[6]][[1]]
[1] "b" "disease2"
I need to get a unique list of first elements into a vector i.e ["a", "b"] from this vector t1
. How can I do this?
Upvotes: 26
Views: 82978
Reputation: 2273
Using base R:
t1 <- list(list("a", "control"), list("a", "disease"), list("b", "control"))
id <- sapply(t1, function(x) {x[[1]]})
unique(id)
Upvotes: 3
Reputation: 8631
As an update in 2020, this is done easily and intuitively with purrr
. Using @Gago-Silva's test list:
library(purrr)
t1 %>% flatten() %>% map(1) %>% as_vector()
Sublists are flattened to character vectors, element 1 is extracted from these and this list of one-element character vectors converted to one vector.
Also note that you can get a tibble back directly from the list of lists with
t1 %>% flatten_dfc()
Upvotes: 5
Reputation: 44614
rapply
offers yet another option:
unique(rapply(t1, function(x) head(x, 1)))
Upvotes: 21
Reputation: 121608
I tried to treat the general case when one or more of the sublists contain more than one element.
For example:
ll <-
list(list(c("a","control")),
list(c("b","disease1")),
list(c("c","disease2"),c("c","disease2bis")), # 2 elements
list(c("d","disease3")),
list(c("e","disease4"))
)
You can do something like this :
unlist(lapply(ll, ## for each element in the big list
function(x)
sapply(1:length(x), ## for each element in the sublist
function(y)do.call("[[",list(x,y))))) ## retrieve x[[y]]
[1] "a" "control" "b" "disease1" "c"
"disease2" "c" "disease2bis" "d" "disease3"
[11] "e" "disease4"
Upvotes: 5
Reputation: 60984
I would use do.call
and rbind
to concatenate the list into a data.frame
. Then you can use unique
on the first column to get the unique items (using the example given by @A.R.):
spam = do.call("rbind", lapply(t1, "[[", 1))
> spam
[,1] [,2]
[1,] "a" "control"
[2,] "b" "disease1"
> unique(spam[,1])
[1] "a" "b"
Upvotes: 15
Reputation: 1971
Another way is to use unlist
:
> t1=list(list(c("a","control")),list(c("b","disease1")))
> t1
[[1]]
[[1]][[1]]
[1] "a" "control"
[[2]]
[[2]][[1]]
[1] "b" "disease1"
> matrix(unlist(t1),ncol=2,byrow=TRUE)
[,1] [,2]
[1,] "a" "control"
[2,] "b" "disease1"
Upvotes: 20