简体   繁体   中英

mutate a column conditionally in dplyr

with a df like below, using dplyr I need to mutate the fields val1, val2, val3 conditionally.

> df <- data.frame(
  id = c(1,2), 
  loc=c("loc1", "loc2"), 
  val1=c(80,64), val2=c(240,32768), val3=c(32768, 64)
)
> df
  id  loc val1  val2  val3
1  1 loc1   80   240 32768
2  2 loc2   64 32768    64

I need set the values in val1, val2, val3 to NA if the value is > 1000

df %>%
 mutuate_at(vars(starts_with("v")), <what goes here>)

We need mutate_at with replace

df %>%
    mutate_at(vars(starts_with("v")), funs(replace(., .>1000, NA)))
#    id  loc val1 val2 val3
#1  1 loc1   80  240   NA
#2  2 loc2   64   NA   64

Your data is in a nontidy format. Tidy it up with gather before mutating:

library(tidyverse)
 df %>% 
  gather("key", "val", val1, val2, val3) %>%
  mutate(val = ifelse(val > 1000, NA, val)) 

If you want to then return you dataframe to its original, nontidy, format, you can use spread

df %>%
  spread(key, val)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM