首页 > 解决方案 > 使用 mutate 和 case_when 时从现有列中插入值

问题描述

当满足 x 列中的条件时,我想向具有相应“y”值的数据框添加一z列。ds

library(tidyverse)
ds <- tibble(x = 1:5,y = 6:10)

ds%>%
  mutate(
    z = case_when(
      x == 3 ~ y,
      TRUE ~ NA_character_
    )
  )

我希望y列中的相应值在z列中,但是如何以正确的方式引用y列?

标签: rdataframedplyr

解决方案


这是你想要的?

ds%>%
  mutate(
    z = case_when(
      x == 3 ~ y,
      TRUE ~ NA_integer_
    )
  )
# A tibble: 5 x 3
      x     y     z
  <int> <int> <int>
1     1     6    NA
2     2     7    NA
3     3     8     8
4     4     9    NA
5     5    10    NA

推荐阅读