I'm in the situation where I would like to create an object from a character vector. For example:
v <- c("ind1_2015", "ind1_2016", "ind1_2017")
for (ind in v) {
ind <- readRDS(paste0(ind, ".RDS"))
}
so at the end I would like to have 3 data frames, each one called ind1_2015, ind1_2016 and ind1_2017. How can I achieve this?
CodePudding user response:
You could use assign
:
v <- c("ind1_2015", "ind1_2016", "ind1_2017")
for(ind in v) {
assign(ind, data.frame(v = ind))
}
CodePudding user response:
assign
can be used here, in this example resulting in three dataframes called df_ind1_2015
, df_ind1_2016
, and df_ind1_2017
:
v <- c("ind1_2015", "ind1_2016", "ind1_2017")
for(ind in v) {
value <- readRDS(paste0(ind, ".RDS"))
assign(x = paste0("df_", ind), value = value)
}
CodePudding user response:
In R this is different from Python or similar. Initialize a named list but loop over the (numeric) indices.
for (i in seq_along(v)) {
ind[[i]] <- readRDS(paste0(v[[i]], ".rds"))
}
ind
# $ind1_2015
# X1 X2 X3 X4
# 1 1 4 7 10
# 2 2 5 8 11
# 3 3 6 9 12
#
# $ind1_2016
# X1 X2 X3 X4
# 1 1 4 7 10
# 2 2 5 8 11
# 3 3 6 9 12
#
# $ind1_2017
# X1 X2 X3 X4
# 1 1 4 7 10
# 2 2 5 8 11
# 3 3 6 9 12
Alternatively use lapply
ind <- lapply(setNames(v, v), \(x) readRDS(paste0(x, '.rds')))
To "unpack" the list use list2env(ind, .GlobalEnv)
to get single data frames (not necessarily recommended).
Data:
ind1_2015 <- ind1_2016 <- ind1_2017 <- data.frame(matrix(1:12, 3, 4))
lapply(c("ind1_2015", "ind1_2016", "ind1_2017"), \(x) saveRDS(get(x), paste0(x, '.rds')))