Home > database >  How to use a function to create multiple dataframes based on arguments in R
How to use a function to create multiple dataframes based on arguments in R

Time:11-19

I have a data frame with a lot of columns having the same ending (a___1, a___2, b___1, b___2, etc). I want different data frames containing the respective columns (df_a contains a___1 and a___2, etc.)

Due to de large numbers of columns in each data frame, I want to do it with a function.

I tried the following function.

create_df_sud_form <- function(x, y){

  noquote(paste("df_sud_form_", x, sep="")) <- data.frame (
    idata[, paste(y, "___1", sep="")],
    idata[, paste(y, "___2", sep="")],
    idata[, paste(y, "___3", sep="")],
    idata[, paste(y, "___4", sep="")],
    idata[, paste(y, "___5", sep="")],
    idata[, paste(y, "___6", sep="")],
    idata[, paste(y, "___7", sep="")],
    idata[, paste(y, "___8", sep="")],
    idata[, paste(y, "___9", sep="")]
  )
}

create_df_sud_form("alk", "l_alk_009")

The code works, if I dont use it in a function. But as soon as I try to run it in a function and use the function, an error appears (translated by google: "The target of the assignment does not expand to any language object").

Thanks for any help!

CodePudding user response:

This is how I would go about it.

library(tidyverse)

df <- tibble(a___1 = 1:10, a___2 = 11:20, b___1 = 1:10, b___2 = 11:20, c___1 = 1:10, c___2 = 11:20)  

split_out <- function(start) {
  out <- df %>% 
    select(starts_with(start))      
  assign(paste0("df_", start), out, envir = .GlobalEnv)      
}

split_out("b")

df_b

 > df_b
# A tibble: 10 × 2
   b___1 b___2
   <int> <int>
 1     1    11
 2     2    12
 3     3    13
 4     4    14
 5     5    15
 6     6    16
 7     7    17
 8     8    18
 9     9    19
10    10    20
  • Related