【问题标题】:(R or EXCEL) Rename variables in a column to the variables in another column(R 或 EXCEL)将一列中的变量重命名为另一列中的变量
【发布时间】:2021-06-22 16:14:43
【问题描述】:

我是 R 的初学者,正在寻求 Excel 或 R 方面的帮助。

我有一个包含两列(所有文本)的 Excel 表。

  • Column1 有大约 100,000 行,是一个冗长名称的列表。
  • Column2 大约有 500 行,是一个缩短名称的列表。

要求:如果Column1中的单元格包含Column2中的任何文本字符串,我需要将Column1中的单元格重命名为Column2中的字符串。 Column2 中的所有字符串都是唯一的,因此不应存在重叠问题。

我无法在 Excel 中计算出来,因为单元格不完全匹配,而且 Excel 的近似匹配太不准确而无法使用。我考虑在 R 中这样做,但列的行数不同,这让我很困惑。非常感谢任何可能的帮助。如果我应该包含更多/其他详细信息,请告诉我。谢谢!

这是 R 中的格式示例(由于行数不同,列是单独的 dfs 除外)

Column1 <- data.frame(Full_Name = c("Geico Auto Insurance",
                  "Geico Motorcycle Insurance",
                  "Geico Commercial Auto Insurance",
                  "State Farm Car Insurance",
                  "State Farm Life Insurance"))
Column2 <- data.frame(Group_Name = c("Geico ",
                                 "State Farm",
                                 "Allstate"))

更多:what the example looks like in excel

【问题讨论】:

  • 嗨,Panon,只是在考虑逻辑。 “Geico State Farm”将映射到什么?也许是“Geico”,因为从左到右工作,这是它找到的第一个?

标签: r excel


【解决方案1】:

我们可以创建一个正则表达式来捕获来自 'Column2' 'Group_Name' 的单词

library(dplyr)
library(stringr)
Column1 %>% 
   mutate(New_Name = str_replace(Full_Name, 
     str_c(".*(", str_c(Column2$Group_Name, collapse="|"),  ").*"), "\\1"))

-输出

                         Full_Name   New_Name
1            Geico Auto Insurance     Geico 
2      Geico Motorcycle Insurance     Geico 
3 Geico Commercial Auto Insurance     Geico 
4        State Farm Car Insurance State Farm
5       State Farm Life Insurance State Farm

【讨论】:

    【解决方案2】:

    库(dplyr) 库(字符串)

    您可以分几个步骤完成:

    1. 为第 2 列创建一个向量

    short_name_vct

    1. 创建函数
    get_match <- function(string) {
    
    
    str_detect(stringr, short_name_vct)[short_name_vct]
    
    }
    
    1. 那么就用dplyr

    df %>% mutate(new_col = get_match(full_name))

    【讨论】:

      【解决方案3】:
      fuzzyjoin::regex_left_join(Column1, Column2, by = c("Full_Name" = "Group_Name"))
      #                         Full_Name Group_Name
      # 1            Geico Auto Insurance     Geico 
      # 2      Geico Motorcycle Insurance     Geico 
      # 3 Geico Commercial Auto Insurance     Geico 
      # 4        State Farm Car Insurance State Farm
      # 5       State Farm Life Insurance State Farm
      

      从这里,您可以重命名Group_Name 并改用它。您会发现NAs 没有正则表达式匹配,因此您可能希望使用dplyr::coalesce 或类似函数来使用第一个非NA 值。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-01-30
        • 2020-07-07
        • 2022-06-29
        • 2021-07-18
        • 2021-04-30
        • 2017-06-09
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多