Home > Enterprise >  R How to get element of data frame based on corresponding value in row?
R How to get element of data frame based on corresponding value in row?

Time:01-16

I have a data frame:

lookup_df <- data.frame(variable_name=c("x", "y", "z", "r"), function_name=c("table", "min", "table", "table"))


  variable_name function_name
1             x         table
2             y           min
3             z         table
4             r         table

I want to be able to get the corresponding function_name depending on a provided variable_name. This is what I have so far but its result is a list, what I want is the actual string value of the function_name

lookup_df %>% filter(variable_name == "x") %>% select("function_name")[function_name]

For example, given the variable_name "z", I should get "table" as a string

CodePudding user response:

I recently learned that there are many ways to do this

Extract a single value from a dataframe/tibble the tidy/dplyr way

but here is the one i like best

library(dplyr)
library(tibble)
library(purrr)

lookup_df %>% deframe() %>% pluck("z")
#> [1] "table"

Created on 2022-01-15 by the reprex package (v2.0.1)

CodePudding user response:

select always returns a dataframe. The correct dplyr verb you should use is pull.

lookup_df %>% filter(variable_name == "x") %>% pull(function_name)

Output

[1] "table"

CodePudding user response:

YOu can add pluck to the bottem line

> lookup_df %>%
    filter(variable_name == "x") %>%
    select(function_name) %>%
    pluck(1)
[1] "table"

CodePudding user response:

Here are couple of base R options -

#1. Using `==`
lookup_df$function_name[lookup_df$variable_name == 'z']
#[1] "table"

#2. Using `match`
lookup_df$function_name[match('z', lookup_df$variable_name)]
#[1] "table"
  •  Tags:  
  • Related