【问题标题】:replace vector of characters using separate dataframe of different length使用不同长度的单独数据框替换字符向量
【发布时间】:2018-04-19 18:38:01
【问题描述】:

有一个字符向量(约 35,000 行)(col1),我想根据单独的数据帧 (df1) 对其进行重新编码/重命名。都是字符向量。

col1
C
B
M A
B
R R
C
R R
M A
B

df1:

V1   V2
B    blanket
C    toy
M A  blarg
R R  targe

结果是

col1
toy
blanket
blarg
blanket
targe
toy
targe
blarg
blanket

我想做的是说“如果 V1 = col1,替换为 V1 = V2” 我试着按字面意思写:

out<-if(col1==df$V1){replace(df$V1 == df$V2)}

抛出:

Warning message:
In if (testdat == schooldf$V1) { :
  the condition has length > 1 and only the first element will be used

我尝试使用 gsub:

out<-gsub(df$V1, df$V2, col1)

抛出:

1: In gsub(schooldf$V1, schooldf$V2, testdat) :
  argument 'pattern' has length > 1 and only the first element will be used
2: In gsub(schooldf$V1, schooldf$V2, testdat) :
  argument 'replacement' has length > 1 and only the first element will be used

显然,我尝试过的两个论点都存在相似的问题,但我无法弄清楚我做错了什么。

【问题讨论】:

    标签: r if-statement gsub


    【解决方案1】:

    您使用replace 代码收到的警告来自您使用if() 的事实,该if() 用于流量控制,而不是变量创建。它仅意味着采用长度为 1 的逻辑值(TRUE 或 FALSE)。 replace 的语法也不正确,请参阅 ?replace 或下面我的答案的最后一部分:

    一个想法是使用match 而不是replacereplace 一次只做一个条件

    col2 <- df1$V2[match(col1, df1$V1)]
    col2
    #[1] "toy"     "blanket" "blarg"   "blanket" "targe"   "toy"     "targe"   "blarg"   "blanket"
    

    结果是一个字符向量,因为您说col1 在您的问题中是什么。如果col1data.frame,您仍然可以使用相同的方法。

    如果您有一些潜在的不匹配项,您可以使用replace 来确保保留原始的col1 值:

    replace(col2, is.na(col2), col1[which(is.na(col2))])
    

    【讨论】:

      【解决方案2】:

      你也可以使用merge,假设你的coldf

      merge(df1, df, by.x = "v1", by.y = "col", all.y=T)

      【讨论】:

        猜你喜欢
        • 2016-09-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-08-04
        • 2017-10-31
        • 2017-07-23
        • 1970-01-01
        相关资源
        最近更新 更多