Reputation: 385
df <- data.frame(intro = c("bob","bob","bob"),
intro_score = c("Excellent","Excellent","Good"),
method = c("sally","sally","sally"),
method_score = c("Excellent","Excellent","Excellent"),
result = c("Norman","Norman","Norman"),
result_score = c("Good","Good","Good"))
If I want to look for "bob" in this dataframe, how do I return the column next to "bob" (intro_score only), assuming I'm not sure if "bob" is in here. Say, if I were to look for "ken", the result should be null. If I were to look for "Norman", the result should return result_score.
I have tried something like this:
name <- "bob"
df_name <- df %>%
if (str_detect(intro, name)) {
select((which(colnames==str_detect(intro, name)))+1)
} else {}
Thank you for your help!
Upvotes: 0
Views: 82
Reputation: 30474
You could reshape your data into time (intro, method, result), name, and score.
df2 <- reshape(df, direction = "long", varying = list(c(1,3,5), c(2,4,6)), v.names = c("name", "score"), times = c("intro", "method", "result"))
df2[df2$name == "Norman", "score"]
Upvotes: 0
Reputation: 79208
using base R if you need the names you could do:
names(df[unique(which(df=="bob",TRUE)[,2]+1)])
[1] "intro_score"
or if you need the column values, you do:
df[unique(which(df=="bob",TRUE)[,2]+1)]
intro_score
1 Excellent
2 Excellent
3 Good
Upvotes: 1
Reputation: 887048
Here is one option with select_if
library(dplyr)
library(magrittr)
df %>%
select_if(~ any(. == "bob")) %>%
names %>%
match(., names(df)) %>%
add(1) %>%
names(df)[.]
#[1] "intro_score"
Upvotes: 0
Reputation: 6106
library(purrr)
search_person <- "bob"
colnames(df)[which(map_lgl(df,~all(.x == search_person))) + 1]
"intro_score"
Upvotes: 0