如何使用dplyr更改原始数据帧的元素

时间:2019-05-22 13:08:40

标签: r dplyr

我有个小标题:

library('tibble')

df <- tibble(
  ticker = c("first", "second", "third"),
  status = c(T,T,T)
)

> df
# A tibble: 3 x 2
  ticker status
 1 first  TRUE  
 2 second TRUE  
 3 third  TRUE  

我想在原始df中将“第一”的状态更改为FALSE。

但是当我运行这段代码时:

library('dplyr')

df %<>%
  filter(ticker=='first') %>%
  mutate(
   status = F
  )

我只有第一行获得原始df

> df
# A tibble: 1 x 2
  ticker status
1 first  FALSE 

代替:

> df
# A tibble: 3 x 2
  ticker status
1 first  FALSE 
2 second TRUE  
3 third  TRUE

2 个答案:

答案 0 :(得分:1)

使用基数

 within(df, status[ticker == "first"] <- FALSE )

答案 1 :(得分:0)

使用功能case_when

library('tibble')

df <- tibble(
    ticker = c("first", "second", "third"),
    status = c(T,T,T)
)

library(tidyverse)

df %>% 
    mutate(status = case_when(
        ticker == "first" ~ F,
        TRUE ~ T
    ))

这是输出:

# A tibble: 3 x 3
  ticker status `case_when(ticker == "first" ~ F, TRUE ~ T)`
  <chr>  <lgl>  <lgl>                                       
1 first  TRUE   FALSE                                       
2 second TRUE   TRUE                                        
3 third  TRUE   TRUE