简体   繁体   English

如何使用 function 在 R 中基于 arguments 创建多个数据帧

[英]How to use a function to create multiple dataframes based on arguments in R

I have a data frame with a lot of columns having the same ending (a___1, a___2, b___1, b___2, etc).我有一个数据框,其中有很多列具有相同的结尾(a___1、a___2、b___1、b___2 等)。 I want different data frames containing the respective columns (df_a contains a___1 and a___2, etc.)我想要包含相应列的不同数据框(df_a 包含 a___1 和 a___2 等)

Due to de large numbers of columns in each data frame, I want to do it with a function.由于每个数据框中的列数很大,我想用 function 来完成。

I tried the following function.我尝试了以下 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").代码有效,如果我不在 function 中使用它。但是一旦我尝试在 function 中运行它并使用 function,就会出现错误(由谷歌翻译:“任务的目标不会扩展到任何语言目的”)。

Thanks for any help!谢谢你的帮助!

This is how I would go about it.这就是我将 go 关于它的方式。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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