简体   繁体   中英

How to (efficiently) retrieve the value of a column in a different row based on matching IDs?

I'm trying to do what I did in the example below, but on a large scale so Ideally the solution is as efficient as possible. Thanks in advance

ID1 <- c("a", "d", "c", "d")
ID2 <- c("d", "e", "f", "g")

df <- data.frame(ID1, ID2)

df

  ID1 ID2
1   a   d
2   d   e
3   c   f
4   d   g

Function that finds "d" in column "ID1", and returns "e" in the first row (where ID1 = "a")

If run again, or specified that we want the second match, function that finds "d" in column "ID1", and returns "g" in the first row (where ID1 = "a")

ID3 <- c("e", "", "", "")
ID4 <- c("g", "", "", "")


desired <- data.frame(ID1, ID2, ID3, ID4)

desired 

  ID1 ID2 ID3 ID4
1   a   d   e   g
2   d   e        
3   c   f        
4   a   g           

We could use

vals <- with(df, ID2[ID1 %in% ID2])
df[1, paste0("ID", seq_along(vals)+2)] <- vals

-output

> df
  ID1 ID2  ID3  ID4
1   a   d    e    g
2   d   e <NA> <NA>
3   c   f <NA> <NA>
4   d   g <NA> <NA>

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