简体   繁体   中英

R replace values in one data frame by values from other data frame wher row values indicate column positions

I have some sort of advanced (?) vlookup problem I'm wondering if it could be done in R (no problem to do in Excel).

I have the following data frame:

dat <- data.frame(Var1 = c(1,2,3,4,5),
                  Var2 = c(5,4,3,2,1),
                  Var3 = c(5,5,5,5,5),
                  Var4 = c(1,1,1,1,1))

In this data frame the values point to the column position from a second data frame:

lookup = data.frame(l1 = c(10,11,12,13,14),
                    l2 = c(20,21,22,23,24),
                    l3 = c(30,31,32,33,34),
                    l4 = c(40,41,42,43,44),
                    l5 = c(50,51,52,53,54))

So looking at dat , first row 3rd column contains a 5, which means I want to replace this value by the first row value, column 5 from the lookup data frame (which is 50). dat[2,2] is supposed to change to 21.

The expected outcome is:

Var1    Var2    Var3    Var4
10      50      50      10
21      41      51      11
...

It's quite simple to do in Excel, but I can't get my head around it in R. I tried sth. along the lines of:

combined = as.data.frame(lapply(dat, function(x) {lookup[, names(lookup) == paste0("l",x)]})) , but this didn't work.

Any suggestions?

We can use a row/column indexing

dat[] <- lookup[cbind(c(row(dat)), unlist(dat))]
dat
#  Var1 Var2 Var3 Var4
#1   10   50   50   10
#2   21   41   51   11
#3   32   32   52   12
#4   43   23   53   13
#5   54   14   54   14

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