Reputation: 1572
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!
Upvotes: 0
Views: 28
Reputation: 389265
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)
Upvotes: 1