首页 > 解决方案 > 如何使用序列中的值作为名称在r中的for循环中命名对象

问题描述

下面是我到目前为止的代码,它不起作用。我有 7 个数据框,每个数据框都包含有关一种污染物的信息(在 中命名pollutant_long_name)。例如,这些数据帧中的每一个都称为national_tier1_Nitrogen Oxidesnational_tier1_Ammonia。我一直在尝试使用该paste0函数在 for 循环中使用我的 for 循环序列中的值,但它似乎不起作用。我得到的第一个错误是

错误:意外的“=”在:“dplyr::group_by(inv_sector) %>%
dplyr::summarise(paste0(“NEI_emissions_”,污染物名称,“_2011”) =

基本上,我的最终目标是调用 7 个数据框total_2011_pollutant name,然后我将leftjoin制作一个包含所有 7 种污染物的数据框。

pollutant_long_name <- c( "Nitrogen Oxides", "Sulfur Dioxide", "Carbon Monoxide", "Volatile Organic Compounds",
                          "PM2.5 Filterable", "PM10 Filterable", "Ammonia" )
for( n in pollutant_long_name ){
  pollutant_name <- paste0( n )
#===================================================================================NOX
NEI_2011 %>%
  dplyr::left_join( CEDS_to_EPA_rename, by = c( "CEDS_Sector" ) ) %>%
  dplyr::filter( pollutant == pollutant_name ) %>%
  dplyr::group_by( inv_sector ) %>%
  dplyr::summarise( paste0( "NEI_emissions_", pollutant_name, "_2011" ) = sum( emissions/1000 ) ) %>%
  round_df( digits = 0 )-> NEI_2011_emissions

paste0( "national_tier1_", pollutant_name ) %>%
  dplyr::select( c(Source.Category, X2011) ) %>%
  dplyr::rename( inv_sector = Source.Category ) %>%
  dplyr::mutate( X2011 = gsub( ",", "", X2011 ) ) %>%
  dplyr::mutate( X2011 = as.numeric(as.character( X2011 ) ) ) %>%
  dplyr::rename( national_2011_NOX = X2011 )-> paste0( "national_2011_", pollutant_name )

NEI_2011_emissions %>%
  dplyr::left_join( paste0( "national_2011_", pollutant_name ), by = c( "inv_sector" ) ) -> paste0( "total_2011_", pollutant_name )
paste0( "total_2011_", pollutant_name )[is.na(paste0( "total_2011_", pollutant_name ))] <- 0
}

标签: rfor-loopdplyr

解决方案


如果我们在lhsof上使用字符串=,它将不起作用,相反我们可以在使用( ):=评估字符串时使用!!

library(dplyr)
NEI_2011 %>%
  dplyr::left_join( CEDS_to_EPA_rename, by = c( "CEDS_Sector" ) ) %>%
  dplyr::filter( pollutant == pollutant_name ) %>%
  dplyr::group_by( inv_sector ) %>%
  dplyr::summarise( !!paste0( "NEI_emissions_",  ## changed
       pollutant_name, "_2011" ) := sum( emissions/1000 ) ) %>% ## changed
  round_df( digits = 0 )-> NEI_2011_emissions

对于用 来创建对象名称的第二个块paste,它仍然是一个字符串。如果我们需要获取字符串对象的值然后使用get(对于多个对象使用mget- 返回一个list对象值)。要将输出分配给对象,请使用assign

assign(paste0( "national_2011_", pollutant_name ), 
   get(paste0( "national_tier1_", pollutant_name )) %>%
   dplyr::select( c(Source.Category, X2011) ) %>%
   dplyr::rename( inv_sector = Source.Category ) %>%
   dplyr::mutate( X2011 = gsub( ",", "", X2011 ) ) %>%
   dplyr::mutate( X2011 = as.numeric(as.character( X2011 ) ) ) %>%
   dplyr::rename( national_2011_NOX = X2011 ))

assign一般来说,全局环境中的多个对象并不是真正需要的。我们可以创建一个list来存储不同值的输出


推荐阅读