【问题标题】:Substitute digits with strings contained in a reference dataframe用参考数据帧中包含的字符串替换数字
【发布时间】:2020-05-22 16:49:07
【问题描述】:

我有一个df_a 看起来像:

df_a <- tibble::tribble(
             ~id,    ~string,
          115088, "1-3-5-13",
          678326, "1-9-13-3",
          105616, "1-3-5-13"
          )

每个 id 都与string 列相关联,该列存储由“-”分隔的数字组成的字符串。

我有一个参考数据框,每个 id_string 都与一个文本字符串相关联。

id <- tibble::tribble(
        ~name, ~id_string,
        "aaa",          1,
        "bbb",          3,
        "ccc",          5,
        "ddd",         13,
        "eee",          9,
        "fff",          8,
        "ggg",          6
        )

我想用存储在参考数据框id 中的文本替换df_astring 列中的数字。

结果应该是:

df_output <- tibble::tribble(
                  ~id,            ~string,
               115088,  "aaa-bbb-ccc-ddd",
               678326, "aaa-eee-ddd- bbb",
               105616,  "aaa-bbb-ccc-ddd"
               )

【问题讨论】:

  • string 列中的数字/破折号组合是否具有一致的长度(每行具有相同数量的数字和破折号)?

标签: r dplyr stringr


【解决方案1】:

是的,你这里有一个非常讨厌的东西,这是我会编写一个专用的 c++ 方法并从 R 调用它的类型,因为在我看来,它有不对称性。

我为您编写了一个迭代循环 - 它可能有效 - 我不确定,但即使它有效并且您的数据超过 200K 行,它也会成为一个问题并且可能需要很长时间才能完成。

temp = strsplit(df_a$string, "-") %>% lapply(function(x) as.numeric(x))
temp.List = list()
actual.List = list()

for(i in 1:length(temp)){
  for (j in 1:nrow(id)){
    if(temp[[i]] %in% id$id_string[j]){
      temp.List[j] = id$name[j]
    }else{
      temp.List[j] = NULL
    }
  }
  actual.List[[i]]= temp.List %>% unlist %>% paste(sep ='-')
}

desired.Output = cbind(df_a$id,actual.List %>% unlist)
#cleanup
rm(temp,temp.List,actual.List)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-05-13
    • 2021-06-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多