R:通过替换过滤和变异数据帧

问题描述 投票:1回答:2

我正在尝试选择所有高于3.0的TRUE值,并将TF列也替换为FALSE。我可以这样做,但是在替换原始数据帧时遇到了麻烦。建议?

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)

最终数据帧应为:

“ TF” = c(“ TRUE”,“ FALSE”,“ FALSE”“ FALSE”,“ FALSE”,“ FALSE”)]

“ Number” = c(4.0,4.0,3.0,2.5,3.0,1.0)

r dplyr
2个回答
1
投票

使用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 = if_else(TF == "TRUE" & Number <= 3, "FALSE", TF))

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

0
投票

Base R可能是您最好的选择

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

如果您真的对tidyverse感兴趣

mutate(df, TF = if_else(TF & (Number <=3), TRUE, TF))
© www.soinside.com 2019 - 2024. All rights reserved.