简体   繁体   中英

Create multiple dataframes or vectors by automation with vector names

Simply put in this example, I have a vector with 3 directions:

vector <- c("South", "North", "East")

And I need to create a new vector for each of the directions and name the 3 new vectors after each direction. So I expected the logic below to work:

for(i in 1:length(vector){ data. vector[i] <- c(1:3)

And it would create 3 vectors (data.South, data.North and data.East) all 3 equal to (1,2,3).

Unfortunately, this does not work as the vector reference vector[1] is read by R as a nonexistent dataframe:

Error in data.vector[1] <- "Position": object 'data.vector' not found

Is there a way I can code it and get the 3 new vectors created?

Thanks a lot!

One approach that is very similar to the way you are asking is with assign :

for(i in seq_along(vector)){
assign(vector[[i]],data.frame())
}
ls()
[1] "East"             "North"             "South"

Another approach is to create a list object where each element is a data.frame , like this:

lapply(vector, function(x){setNames(data.frame(x),x)})
[[1]]
  South
1 South

[[2]]
  North
1 North

[[3]]
  East
1 East

If you want to create empty dataframes with names in vector , one way would be:

list_data <- setNames(replicate(length(vector), data.frame()), 
                      paste0('data.', vector))
list2env(list_data, .GlobalEnv)

However, consider using lists ( list_data ) as they are easier to manage and do not pollute the global environment.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM