【问题标题】:Changing multiple strings in column inside a function tidyverse style在函数tidyverse样式内更改列中的多个字符串
【发布时间】:2021-04-18 05:12:09
【问题描述】:

对于下面的数据框

> df <- data.frame(Country = c("Republic of Ireland", "United Kingdom", "United States of America"))
# Country
# <chr>
# Republic of Ireland               
# United Kingdom                
# United States of America

我有没有办法通过使用函数(tidyverse 样式)来更改国家/地区名称。我还希望能够引用数据框中的特定列。

这是我到目前为止所做的:

# c("Old name", "new name")
name_change = list(c("Republic of Ireland", "Ireland"), 
                   c("United Kingdom", "UK"),
                   c("Russia Moscow", "Russia"),
                   c("United States of America", "USA"))


name_change_func <- function(vec, data = c2, df_col = Country){
  # Expecting vec c("Old name", "new name")
  old_n <- vec[1]
  new_n <- vec[2]
  data %>% 
    mutate(!!df_col = gsub(old_n, new_n, !!df_col ))
}

map_df(name_change, ~name_change_func(.x)) %>%
  group_by(Country) %>%
  filter(row_number(Country) == 1)

这不起作用,但是如果我们将 !!df_col 直接更改为 Country,它将起作用(有点,会得到需要过滤掉的重复名称,我们并没有真正更改名称,而是添加行) .

有没有办法解决这个问题?能够将函数参数用作函数内的列。
如果您知道更好的解决方案,可以加分。

【问题讨论】:

    标签: r string function dplyr tidyverse


    【解决方案1】:

    另一种选择是tidyverse 中的case_when

    library(dplyr)
    
    df <- data.frame(Country = c("Republic of Ireland", "United Kingdom", "United States of America"))
    
    df <- 
      df %>% 
      dplyr::mutate(NewCountry = 
        case_when(
          Country == "Republic of Ireland" ~ "Ireland",
          Country == "United States of America" ~ "US",
          Country == "United Kingdom" ~ "UK",
          Country == "Russia Moscow" ~ "Russia"
        )
      )
    #                    Country NewCountry
    # 1      Republic of Ireland    Ireland
    # 2           United Kingdom         UK
    # 3 United States of America         US
    

    【讨论】:

      【解决方案2】:

      您可以使用命名向量来替换,它可以在str_replace_all 中使用。

      library(dplyr)
      library(stringr)
      
      #c("Old name" = "new name")
      name_change = c("Republic of Ireland" = "Ireland", 
                       "United Kingdom" = "UK",
                       "Russia Moscow" = "Russia",
                       "United States of America" = "USA")
      
      df %>% mutate(new_country = str_replace_all(Country, name_change))
      
      #                   Country new_country
      #1      Republic of Ireland     Ireland
      #2           United Kingdom          UK
      #3 United States of America         USA
      

      【讨论】:

        猜你喜欢
        • 2021-03-26
        • 1970-01-01
        • 2022-11-30
        • 1970-01-01
        • 2019-06-07
        • 2021-09-19
        • 1970-01-01
        • 1970-01-01
        • 2012-10-09
        相关资源
        最近更新 更多