Reputation: 958
I have a list within a data frame (in this example, df$candpct
), and would like to extract the first and second elements from the list and place them into separate vectors.
Here is the initial structure of the data frame:
> head(df)
juris candpct
1 101 0.752491, 0.247509
2 102 0.4856056, 0.2850754, 0.1845157
3 103 1
4 104 1
I've looked at this answer, which showed me how to extract the first element effectively:
> df$first_place <- sapply(df$candpct,"[[",1)
> head(df)
juris candpct first_place
1 101 0.752491, 0.247509 0.752491
2 102 0.4856056, 0.2850754, 0.1845157 0.4856056
3 103 1 1
4 104 1 1
But if I try and run another line to extract the second element, I get an error as not all rows have an element in the second position.
> df$second_place <- sapply(df$candpct,"[[",2)
Error in FUN(X[[3L]], ...) : subscript out of bounds
Ideally, I'd like for it to fill the corresponding row in second_place
with NA
or 0
if the second element is missing.
I'm sure there are various approaches for how to deal with this problem, but I don't have a lot of experience working with lists so I'm having a lot of trouble getting started.
Thanks in advance for your help.
Upvotes: 2
Views: 1028
Reputation: 173677
Just following up on my comment:
l <- list(a = 1,b = 1:2,c = 1:3)
> sapply(l,'[',2)
a b c
NA 2 2
Upvotes: 3