【问题标题】:Replace values with a "translation" from another table用另一个表中的“翻译”替换值
【发布时间】:2021-05-03 14:52:08
【问题描述】:

所以我对 R 比较陌生,我遇到了以下问题,我还没有找到答案。

我有两张桌子,其中一张

ID German
1 Hallo
3 Katze
4 Hund

还有一个有英文翻译的。

English German
hello Hallo
cat Katze
dog Hund

我想做的是用第二个表中的英文术语替换第一个表中的德语单词。我该怎么做?

提前感谢您的帮助!

【问题讨论】:

    标签: r dataframe replace subset extract


    【解决方案1】:

    你可以试试下面的代码

    > merge(df1,df2)[-1]
      ID English
    1  1   hello
    2  4     dog
    3  3     cat
    

    data.table 选项

    > setDT(df1)[setDT(df2),on = .(German)][,German:=NULL][]
       ID English
    1:  1   hello
    2:  3     cat
    3:  4     dog
    

    数据

    > dput(df1)
    structure(list(ID = c(1L, 3L, 4L), German = c("Hallo", "Katze",
    "Hund")), class = "data.frame", row.names = c(NA, -3L))
    
    > dput(df2)
    structure(list(English = c("hello", "cat", "dog"), German = c("Hallo",
    "Katze", "Hund")), class = "data.frame", row.names = c(NA, -3L
    ))
    

    【讨论】:

      【解决方案2】:

      match 的选项来自base R

      df1$English <-  with(df1, df2$English[match(German, df2$German)])
      df1[c("ID", "English")]
      

      数据

      df1 <- structure(list(ID = c(1L, 3L, 4L), German = c("Hallo", "Katze",
       "Hund")), class = "data.frame", row.names = c(NA, -3L))
       
      df2 <- structure(list(English = c("hello", "cat", "dog"), German = c("Hallo",
       "Katze", "Hund")), class = "data.frame", row.names = c(NA, -3L
       ))
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-01-01
        • 1970-01-01
        • 2021-12-25
        • 1970-01-01
        • 2021-06-16
        • 2021-10-11
        • 2019-04-10
        • 2020-03-20
        相关资源
        最近更新 更多