我的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)
我想添加一列,以查找DF名称中“键”中的值,并以该列中的值作为行。我的结果将如下所示:
df$result <- c("C","B","D","E","F")
请注意,“键”列中的值仅部分匹配df的列名,而不是列名的完整名称。我怀疑我需要在某个地方使用grep
或grepl
。我已经尝试了以下代码的变体,但无法正常工作,并且不确定在这种情况下如何应用grep
或grepl
。
df$result <- mapply(function(a) {df[[as.character(a)]]}, a=df$key)
答案 0 :(得分:0)
也许带有“ 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
答案 1 :(得分:0)
将apply
与margin = 1
一起使用(逐行),我们需要使用grepl
来获取值,这有助于检测模式。
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
mapply
的另一种选择是找出需要使用sapply
提取值的列,然后从每一行中获取相应的值。
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