我正在尝试选择所有高于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)
使用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
Base R可能是您最好的选择
df[df$TF & df$Number <= 3, "TF"] <- FALSE
如果您真的对tidyverse感兴趣
mutate(df, TF = if_else(TF & (Number <=3), TRUE, TF))