Astetr
Astetr

Reputation: 79

Replacing a dataframe values with other from a list

I have a dataframe:

col1,col2,
sth1,sth2,
sth2,sth1,
sth3,sth2

and a list with one column with the values from df and the second column with equal other names:

valuesdf,valuesnew
sth1,vn1
sth2,vn2
sth3,vn3

I would like to change the values from the initial dataframe with the equal values from the second dataframe and have as result this:

col1,col2,
vn1,vn2,
vn2,vn1,
vn3,vn2

How is it possible to make it?

Upvotes: 1

Views: 40

Answers (1)

akrun
akrun

Reputation: 887048

We can do a match by looping over the columns of the first dataset ('df1') with the 'valuesdf' column of second, and use that index to get the corresponding 'valuesnew' from 'df2'

df1[] <- lapply(df1, function(x) df2$valuesnew[match(x, df2$valuesdf)])

Upvotes: 1

Related Questions