R 使用不同长度的单独数据帧替换字符向量

R 使用不同长度的单独数据帧替换字符向量,r,if-statement,gsub,R,If Statement,Gsub,有一个字符向量(~35000行)(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” 我试着逐字写

有一个字符向量(~35000行)(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)}
我试着使用gsub:

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

显然,我尝试过的两个参数中的问题是相似的,但我无法找出我做错了什么。

您在
替换
代码中得到的警告来自这样一个事实,即您使用了
if()
,它用于流控制,而不是变量创建。它仅用于获取长度为1的逻辑值(TRUE或FALSE)。另外,
replace
的语法不正确,请参阅
?replace
或下面我回答的最后一部分:

一种方法是使用
匹配
,而不是
替换
<代码>更换
一次只执行一个条件

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

您还可以使用
merge
,前提是您的
col
位于
df

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

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
col2 <- df1$V2[match(col1, df1$V1)]
col2
#[1] "toy"     "blanket" "blarg"   "blanket" "targe"   "toy"     "targe"   "blarg"   "blanket"
replace(col2, is.na(col2), col1[which(is.na(col2))])