簡體   English   中英

使用mutate和case_when時,從現有列中插入值

[英]Insert values from an existing column when using mutate and case_when

當滿足x列中的條件時,我想將z列添加到具有相應“ y”值的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列呢?

這是你想要的?

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM