I have a data set that includes a variable where some of the cases have nested vectors, i.e. some of the cases are just a string, while other cases are vectors of length 2. I would like to make a new variable that just includes the second element of the nested vectors for the cases where there is a nested vector, and is NA if there is no nested vector.
A reproducible example is below:
df <- list(id = 1:5,
answer = list("Agree",
c("Agree", "Strongly Agree"),
c("Disagree", "Agree"),
"Disagree",
c("Disagree", "Strongly Disagree")))
I would like to make a new column in my data frame that has the values
NA, "Strongly Agree", "Agree", NA, "Strongly Disagree"
in that order; in other words, the second element of the vectors where there is a vector, and NA if there is not a vector.
I have attempted to use a mutate() function, as follows:
df %>%
mutate(answer_split = case_when(length(answer) == 2 ~ answer[[??]][2]))
I am unsure what to put in the place of the ??, or if the mutate()/case_when() combination is the correct one.
Any assistance—either guidance on how to complete the above code, or pointing me in the right direction towards a different method—would be greatly appreciated!