Home > OS >  How to select a value in a column based on another column?
How to select a value in a column based on another column?

Time:01-12

I would like to extract the value of a column based on the result of another column

This is my example : In this example the indiv value can be modified. I want to obtain the value "Paul" if the indiv value is "19125", but I want to obtain the value "2022" if the indiv value is "19".

indiv<-19125
df<-data.frame(Code_barre = c(19124, 19125, 19132, 19131),
                   ID = c("Jean","Paul","Marie","Georges"),
                   cross = c(18,15,19,20), 
                   Names = c("2020","2021","2022", "2023"))

this is what I tried :

df%>% filter(Code_barre%in% indiv|cross %in% indiv)%>%
select(if(Code_barre%in% indiv){ID}else
  if(cross%in% indiv){Names})

first I filter the corresponding row and then I make a conditional selection of the column, but it is not working... Any idea ?

CodePudding user response:

You can do a simple if/else function:

f <- function(indiv){
  if(indiv %in% unique(df$Code_barre)){
      df$ID[df$Code_barre == indiv]
    } else if(indiv %in% unique(df$cross)){
      df$Names[df$cross == indiv]
    }
  }

f(indiv = 19125)
#[1] "Paul"

f(indiv = 19)
#[1] "2022"

CodePudding user response:

Here is a function that solves the problem.

df <- data.frame(Code_barre = c(19124, 19125, 19132, 19131),
               ID = c("Jean","Paul","Marie","Georges"),
               cross = c(18,15,19,20), 
               Names = c("2020","2021","2022", "2023"))

library(dplyr)
#> 
#> Attaching package: 'dplyr'
#> The following objects are masked from 'package:stats':
#> 
#>     filter, lag
#> The following objects are masked from 'package:base':
#> 
#>     intersect, setdiff, setequal, union

filter_indiv <- function(data, indiv) {
  data %>%
    mutate(keep = nchar(indiv) == nchar(Code_barre),
           result = ifelse(keep, ID, Names),
           keep = if_else(keep, Code_barre == indiv, cross == indiv)) %>%
    filter(keep) %>%
    pull(result)
}  

indiv <- 19125
filter_indiv(df, indiv)
#> [1] "Paul"

indiv <- "19"
filter_indiv(df, indiv)
#> [1] "2022"

Created on 2023-01-11 with reprex v2.0.2

  • Related