【问题标题】:Turning data manipulation into a function in R将数据操作转换为 R 中的函数
【发布时间】:2021-07-25 01:56:07
【问题描述】:

我从this website(英国国家统计局)下载了一个 .ods 文件。由于工作表的结构方式,我将其作为两个单独的数据框导入:

library(readODS)
income_pretax <- read_ods('/Users/c.robin/Downloads/NS_Table_3_1a_1819.ods', range = "A4:U103")
income_posttax <- read_ods('/Users/c.robin/Downloads/NS_Table_3_1a_1819.ods', range = "A104:U203")

我想对两个数据框进行一些清理:更改两个变量的名称并将其中一个变量重铸为数字。这就是我所拥有的,它适用于单个 df:

income_pretax <- income_pretax %>% 
  rename(pp_tot_income_pretax = 'Percentile point\nTotal income before tax',
         '2008-09' = '2008-09(a)')

income_pretax['2008-09'] <- as.numeric(income_pretax$'2008-09')

不过,我正在努力将上述内容转化为函数。我认为它应该是 something 如下所示,但老实说,我不知道如何告诉 R 我正在将多个数据帧传递给函数,也不知道如何处理多个变量。 谁能就此提出建议?

##Attempting a function
cleanvars <- function(data, varlist){
  data <- data %>% 
    rename(pp_tot_income_pretax = {{varlist}})
  
  data['2008-09'] <- as.numeric(data$'2008-09')
}

【问题讨论】:

    标签: r function dplyr rename


    【解决方案1】:

    您可以将命名向量传递给函数。

    library(dplyr)
    
    cleanvars <- function(data, varlist){
       data %>% rename(varlist)
    }
    
    cleanvars(mtcars %>% head, c('new_mpg' = 'mpg', 'new_cyl' = 'cyl'))
    
    #                  new_mpg new_cyl disp  hp drat    wt  qsec vs am gear carb
    #Mazda RX4            21.0       6  160 110 3.90 2.620 16.46  0  1    4    4
    #Mazda RX4 Wag        21.0       6  160 110 3.90 2.875 17.02  0  1    4    4
    #Datsun 710           22.8       4  108  93 3.85 2.320 18.61  1  1    4    1
    #Hornet 4 Drive       21.4       6  258 110 3.08 3.215 19.44  1  0    3    1
    #Hornet Sportabout    18.7       8  360 175 3.15 3.440 17.02  0  0    3    2
    #Valiant              18.1       6  225 105 2.76 3.460 20.22  1  0    3    1
    

    【讨论】:

    • 太棒了!非常感谢。澄清一下,是否也可以在同一函数中将“2008-09”变量转换为数字变量?另外,您知道如何在模式上进行重命名匹配吗?在我的数据框中,旧名称略有不同('Percentile ... before ...'和'Percentile ... after ...'),所以我想为函数提供类似c('pp_tot_income' = 'Percentile point\nTotal' where 'Percentile point\ nTotal' 是一个包含两个变量的正则表达式
    • 例如,按照你上面所做的,我尝试了类似cleanvars(income %&gt;% head, c('pp_tot_income' = starts_with('Percentile point'), '2008-09' = '2008-09(a)')) 的东西,但这会返回错误
    • 要将'2008-09' 变量转换为数字,您可以添加行%&gt;% mutate(`2008-09` = as.numeric(`2008-09`))。就重命名而言,我不确定这将如何工作。 c('pp_tot_income' = starts_with('Percentile point')...) 因为您需要在数据集中有一个唯一的列名,在这里您是说将所有以 'Percentile point' 开头的列替换为 pp_tot_income ?所以你用一个列名替换多个列?那是行不通的。
    【解决方案2】:

    我们可以在base R这样做

    nm1 <- c('mpg', 'cyl')
    nm2 <- paste0("new_", nm1)
    i1 <- match(nm1, names(mtcars))
    names(mtcars)[i1] <- nm2
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-07-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-06
      • 1970-01-01
      • 1970-01-01
      • 2017-07-24
      相关资源
      最近更新 更多