简体   繁体   中英

Lookup value from DF column in df col names, take value for corresponding row

My DF:

dataAB <- c("A","B","A","A","B")
dataCD <- c("C","C","D","D","C")
dataEF <- c("F","E","E","E","F")
key <- c("dataC","dataA","dataC","dataE","dataE")
df <- data.frame(dataAB,dataCD,dataEF,key)

I'd like to add a column that looks for the value in "key" in the names of the DF and takes the value in that column for the row. My result would look like this:

df$result <- c("C","B","D","E","F")

Note that the value in the "key" column only partially matches the col names of df and is not the complete names of the col names. I suspect I'll need grep or grepl somewhere. I've tried variations on the following code, but can't get anything to work, and I'm unsure how to apply grep or grepl in this case.

df$result <- mapply(function(a) {df[[as.character(a)]]}, a=df$key)

Perhaps, with 'tidyverse' :

df <- data.frame(dataAB,dataCD,dataEF,key,stringsAsFactors=FALSE) %>% mutate(id=row_number())
df %>% gather(k,v,-key,-id) %>% 
 filter(str_detect(substring(k,5),substring(key,5))) %>%
 select(result=v,id) %>% 
 inner_join(df,.,by="id")
#  dataAB dataCD dataEF   key id result
#1      A      C      F dataC  1      C
#2      B      C      E dataA  2      B
#3      A      D      E dataC  3      D
#4      A      D      E dataE  4      E
#5      B      C      F dataE  5      F

Using apply with margin = 1 (row-wise) from which column we need to take the value using grepl which helps to detect the pattern.

df$result <- apply(df, 1, function(x) x[grepl(x["key"], names(x))])
df

#  dataAB dataCD dataEF   key result
#1      A      C      F dataC      C
#2      B      C      E dataA      B
#3      A      D      E dataC      D
#4      A      D      E dataE      E
#5      B      C      F dataE      F

Another option with mapply would be to find out the columns from where we need to extract the values using sapply and then get the corresponding value from each row.

df$result <- mapply(function(x, y) df[x, y], 1:nrow(df), 
            sapply(df$key, function(x) grep(x, names(df), value = TRUE)))

df

#  dataAB dataCD dataEF   key result
#1      A      C      F dataC      C
#2      B      C      E dataA      B
#3      A      D      E dataC      D
#4      A      D      E dataE      E
#5      B      C      F dataE      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