用参考数据框中包含的字符串替换数字

问题描述 投票:1回答:1

我有一个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
        )

我想用存储在参考数据帧string中的文本替换df_aid列中的数字。

结果应该是:

df_output <- tibble::tribble(
                  ~id,            ~string,
               115088,  "aaa-bbb-ccc-ddd",
               678326, "aaa-eee-ddd- bbb",
               105616,  "aaa-bbb-ccc-ddd"
               )
r dplyr stringr
1个回答
0
投票

是的,您在这里遇到了一个非常讨厌的人,这是我会编写专用的c ++方法并从R调用它的类型,因为如我所见,它具有不对称性。

我为您编写了一个迭代循环-可能会工作-不确定,但是即使这样做,并且您的数据超过20万行,也会成为问题,并且可能需要很长时间才能完成。

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)
© www.soinside.com 2019 - 2024. All rights reserved.