Reputation: 75
I would like to create vectors from dataframe rows and use one of the cell values as the vector name. For example:
df <- data.frame(name=c("michel","nadia","carole"),
cities=c("Paris,Montreal","Chicago,Denver","Beijing,Bankok"))
...and I would like to get a vector (for example from the first row), like this:
michel <- c("Paris","Montreal")
How can we do this in R?
Thanks!
Michel
Upvotes: 0
Views: 589
Reputation: 28675
It's worth noting that data frames in R can have list columns, so you could just convert the cities
column to a list of vectors. That way everything is still organized neatly in a data.frame and you can access vectors for specific names by subsetting the data frame
df$cities <- strsplit(as.character(df$cities), ',')
df
# name cities
# 1 michel Paris, Montreal
# 2 nadia Chicago, Denver
# 3 carole Beijing, Bankok
df$cities[[which(df$name == 'michel')]]
# [1] "Paris" "Montreal"
Upvotes: 1
Reputation: 886938
We can use split
into a list
of named vectors and use list2env
for creating multiple objects in the global env (not recommended)
list2env(split(as.character(df$cities), df$name), envir = .GlobalEnv)
If we need to separate the 'cities'
library(dplyr)
library(tidyr)
df %>%
separate_rows(cities) %>%
{split(as.character(.$cities), .$name)} %>%
list2env(.GlobalEnv)
and now check the ls()
for the 'name' objects created in the global env
Or another option is to extract the elements into a list
, then convert it to a named list with deframe
and use list2env
library(purrr)
library(tibble)
library(stringr)
df %>%
mutate(cities = str_extract_all(cities, "\\w+")) %>%
deframe %>%
list2env(.GlobalEnv)
Or for a single row
assign(as.character(df$name)[1],
scan(text = as.character(df$cities)[1], what = "", sep=","))
Now, check the ls()
and the 'michel' object would be found
michel
#[1] "Paris" "Montreal"
Upvotes: 2
Reputation: 6628
First we split the city names into vectors:
cities <- strsplit(as.character(df$cities), ",")
And we give the list entries the names and use list2env()
to copy each entry to the global environment:
names(cities) <- df$name
list2env(cities, envir = .GlobalEnv)
The result are vectors containing the city names in separated entries, for each name:
> michel
[1] "Paris" "Montreal"
> nadia
[1] "Chicago" "Denver"
> carole
[1] "Beijing" "Bankok"
Upvotes: 1