R语言 如何根据另一列选择列中的值?

0dxa2lsx  于 2023-01-15  发布在  其他
关注(0)|答案(2)|浏览(198)

我想根据一列的结果提取另一列的值
这是我的例子:在这个例子中,indiv的值可以修改。如果indiv的值是“19125”,我想获得值“Paul”,但是如果indiv的值是“19”,我想获得值“2022”。

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"))

这就是我所尝试的:

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

首先我过滤了相应的行,然后有条件地选择了列,但是它不起作用......有什么想法吗?

6za6bjd0

6za6bjd01#

您可以执行一个简单的if/else函数:

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"
juud5qan

juud5qan2#

这里有一个函数可以解决这个问题。

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"

创建于2023年1月11日,使用reprex v2.0.2

相关问题