Ana Catarina Vitorino
Ana Catarina Vitorino

Reputation: 85

Using a string to create a function name

Does anyone know a way to return three dataframes with similar names without copying and pasting?

Basically a way to write this:

  mean_dbh <- aggregate(dbh ~ date + plot, data, mean)
  mean_agb <- aggregate(agb ~ date + plot, data, mean)
  mean_ba <- aggregate(ba ~ date + plot, data, mean)

something like

for (val in c('dbh','agb','ba)){
  mean_'val' <- aggregate(val ~ date + plot, data, mean)
}

Upvotes: 1

Views: 61

Answers (2)

Zhiqiang Wang
Zhiqiang Wang

Reputation: 6759

Alternatively, you could try this. First, generate one data frame with all variables and then select each variable for a new file:

library(dplyr)
df <- aggregate(cbind(dbh,agb,ba)  ~ date + plot, data, mean)
val <- c('dbh','agb','ba')
for (i in seq(length(val))){
  assign(paste0('mean_', val[i]), df %>% select(date, plot, val[i]))}

Upvotes: 2

MrFlick
MrFlick

Reputation: 206197

In R we try to avoid creating variables with values stored in the variable names. It makes working with those data.frames much more difficult in general. It's better to work with related values in a list. Here's an alternate way to tackle your problem

vars <- c("dbh","agb","ba")
mean_var <- vars |>
  sapply(function(x) reformulate(c("date","plot"), response = x)) |>
  lapply(function(x) aggregate(x, data, mean)) |>
  setNames(vars)

This will create a list and you can extract the values with

mean_var$dbh
mean_var$agb
mean_var$ba
# or...
mean_var[[1]]
mean_var[[2]]
mean_var[[3]]

Upvotes: 1

Related Questions