2

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.

Community
  • 1
  • 1
bosbmgatl
  • 928
  • 3
  • 9
  • 12

1 Answers1

3

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 
joran
  • 169,992
  • 32
  • 429
  • 468
  • Hm. I guess I should have tried that! Thanks! Was there a change in how this worked in the two years since the answer I link to was posted? – bosbmgatl Apr 07 '12 at 02:18
  • @user1202761 No, I think that [ and [[ have always been like that. – joran Apr 07 '12 at 03:01