简体   繁体   中英

How to replace 1's in each column using a lookup table

I have a data frame (test_df) and a lookup list (key). I would like to replace the 1's in test_df with a value using key. key has only a subset of the column names, and not in the same order. So lookup the value for "dog" in key (5), and replace the 1's in the "dog" column with 5 in test_df.

test_df

cat dog monkey bear
1 1 0 2
2 1 1 1
0 2 2 0

key

dog cat bear
5 6 7

desired output

cat dog monkey bear
6 5 0 2
2 5 1 7
0 2 2 0

thanks for your help.

We can loop through the columns using Map and replace the 1s with the corresponding values of 'key' column

test_df[names(key)] <- Map(function(x, y) replace(x, x==1, y), test_df[names(key)], key)
test_df
#  cat dog monkey bear
#1   6   5      0    2
#2   2   5      1    7
#3   0   2      2    0
for(f in names(key)){
col.num = which(names(test_df) == f) 
test_df[(which(test_df[,col.num] == 1)),col.num] = key[,f] 
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM