0

Having a df such as this:

df <- structure(list(V1 = c("1", "2", "3", "4", "5", "6"), 
               V2 = c("Cat,Dog","Fish,Bird", "Cat, Fish, Bird", "Cat", "Dog, Bird", "Owl, Dog")), 
               class = "data.frame",
               row.names = c(NA,-6L))

I filter by an specific value, say 1:

df <- df %>% filter(V1 == 1)

How can I save the results of V2 in multiple string variables (not in the df),

say V2_1 = "Cat" and V2_1 = "Dog"

Note that when dealing with V1 == 3 now I have 3 variables V2_1,V2_2,V2_3.

Thx!

1 Answer 1

1

You could split the string on "," and get vector.

library(dplyr)    
df <- df %>% filter(V1 == 1)
tmp <- unlist(strsplit(df$V2, ','))

If you want data as separate variables like V2_1 , V2_2 you can use list2env.

list2env(setNames(as.list(tmp), paste0('V2_', seq_along(tmp))), .GlobalEnv)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.