R: Filtering and mutating a data frame WITH replacement

Viewed 776

I am attempting to select all TRUE values that are above 3.0 and replace the TF column too FALSE. I can do this but am having trouble replacing it in the original data frame. Suggestions?

df <- data.frame("TF" = c("TRUE", "FALSE", "TRUE", "TRUE", "FALSE", "FALSE"),
                 "Number" = c(4.0, 4.0, 3.0, 2.5, 3.0, 1.0))


df %>%
  filter(TF == TRUE) %>%
  filter(Number <= 3) %>%
  mutate(TF = FALSE)

The final data frame should be:

"TF" = c("TRUE", "FALSE", "FALSE", "FALSE", "FALSE", "FALSE")

"Number" = c(4.0, 4.0, 3.0, 2.5, 3.0, 1.0)

3 Answers

How about:

df%>% mutate(TF = as.logical(TF))%>% mutate(TF = ifelse(TF & Number <= 3.0, F, TF).

Base R may be your better bet here

df[df$TF & df$Number <= 3, "TF"] <- FALSE

If you're really set on tidyverse

mutate(df, TF = if_else(TF & (Number <=3), FALSE, TF))

Using dplyr

library(dplyr)


df <- data.frame("TF" = c("TRUE", "FALSE", "TRUE", "TRUE", "FALSE", "FALSE"),
                 "Number" = c(4.0, 4.0, 3.0, 2.5, 3.0, 1.0))


df <- df %>%
  mutate(TF = as.character(TF)) %>%
  mutate(TF = if_else(TF == "TRUE" & Number <= 3, "FALSE", TF))

df

df
#>      TF Number
#> 1  TRUE    4.0
#> 2 FALSE    4.0
#> 3 FALSE    3.0
#> 4 FALSE    2.5
#> 5 FALSE    3.0
#> 6 FALSE    1.0
Related