Reputation: 5049
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>)
Upvotes: 2
Views: 1096
Reputation: 5008
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)
Upvotes: 1
Reputation: 886928
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
Upvotes: 3