jeudi 19 avril 2018

replace vector of characters using separate dataframe of different length

There is a character vector (~35,000 rows) (col1) that I would like to recode/rename based on a separate dataframe (df1). They are all character vectors.

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

The outcome would be

col1
toy
blanket
blarg
blanket
targe
toy
targe
blarg
blanket

What I am trying to do is say "if V1 = col1, replace with V1 = V2" I tried to write that literally:

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

which throws:

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

And I tried to use gsub:

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

which throws:

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

Clearly the issue is similar in both arguments I tried, but I'm not able to figure out what I'm doing wrong.

Aucun commentaire:

Enregistrer un commentaire