使用函数向R中的 Dataframe 添加列

eyh26e7m  于 2023-01-28  发布在  其他
关注(0)|答案(1)|浏览(147)

我正在尝试使用一个函数向R中的 Dataframe 添加一列。该函数将简单地连接 Dataframe 中的现有字段,并将连接后的值添加为一个新列:

year <- c(2017, 2018, 2019, 2020, 2017, 2018, 2019, 2020, 2017, 2018, 2019, 2020, 2017, 2018, 2019, 2020)
drugType <- c('drug1', 'drug1', 'drug1', 'drug1', 'drug2', 'drug2', 'drug2', 'drug2', 'drug3', 'drug3', 'drug3', 'drug3', 'drug4', 'drug4', 'drug4', 'drug4')
total <- c(21, 18, 17, 10, 1, 1, 3, 4, 192, 242, 111, 234, 34, 26, 36, 17)
perCapitaRate <- c(1.4, 4.3, 3.4, 3.0, 23.0, 3.3, 3.4, 3.5, 3.6, 45.4, 4.4, 4.5, 23.6, 34.7, 22.3, 2.0)
drugDeathsByYr <- data.frame(year, drugType, total, perCapitaRate)


concat_fields <- function(df) {
  df$year_drug <- paste(df$year, df$drugType, sep="_")
  
}

concat_fields(drugDeathsByYr)

但是,当我运行这个命令时,df drugDeathsByYr没有添加的列。
谢谢。

wi3ka0sx

wi3ka0sx1#

只是return是赋值,而不是数据

concat_fields <- function(df) {
  df$year_drug <- paste(df$year, df$drugType, sep="_")
  df
  
}

现在运行

drugDeathsByYr <- concat_fields(drugDeathsByYr)
> drugDeathsByYr
   year drugType total perCapitaRate  year_drug
1  2017    drug1    21           1.4 2017_drug1
2  2018    drug1    18           4.3 2018_drug1
3  2019    drug1    17           3.4 2019_drug1
4  2020    drug1    10           3.0 2020_drug1
5  2017    drug2     1          23.0 2017_drug2
6  2018    drug2     1           3.3 2018_drug2
7  2019    drug2     3           3.4 2019_drug2
8  2020    drug2     4           3.5 2020_drug2
9  2017    drug3   192           3.6 2017_drug3
10 2018    drug3   242          45.4 2018_drug3
11 2019    drug3   111           4.4 2019_drug3
12 2020    drug3   234           4.5 2020_drug3
13 2017    drug4    34          23.6 2017_drug4
14 2018    drug4    26          34.7 2018_drug4
15 2019    drug4    36          22.3 2019_drug4
16 2020    drug4    17           2.0 2020_drug4

如果要更新全局env中的原始对象,请使用envir作为参数并更新

concat_fields <- function(df, envir = .GlobalEnv) {
  tmp <- deparse(substitute(df))
  envir[[tmp]]$year_drug <- paste(df$year, df$drugType, sep="_")
  
}

concat_fields(drugDeathsByYr)
  • 输出
> drugDeathsByYr
   year drugType total perCapitaRate  year_drug
1  2017    drug1    21           1.4 2017_drug1
2  2018    drug1    18           4.3 2018_drug1
3  2019    drug1    17           3.4 2019_drug1
4  2020    drug1    10           3.0 2020_drug1
5  2017    drug2     1          23.0 2017_drug2
6  2018    drug2     1           3.3 2018_drug2
7  2019    drug2     3           3.4 2019_drug2
8  2020    drug2     4           3.5 2020_drug2
9  2017    drug3   192           3.6 2017_drug3
10 2018    drug3   242          45.4 2018_drug3
11 2019    drug3   111           4.4 2019_drug3
12 2020    drug3   234           4.5 2020_drug3
13 2017    drug4    34          23.6 2017_drug4
14 2018    drug4    26          34.7 2018_drug4
15 2019    drug4    36          22.3 2019_drug4
16 2020    drug4    17           2.0 2020_drug4

相关问题