若变量满足条件,则替换另一个变量R的值



我一直在寻找类似问题的各种答案,但找不到任何能完全回答我问题的答案。

我有一个大数据表

Number_X 金额
1 100
2 100
1 100
3 100
1 100
2 100
# set as data.table
setDT(df)
# if then
df[ Number_X == 1, Amount := 50]

对于大数据,data.table解决方案是最合适的。

我认为使用replace()没有问题,但您也可以尝试使用if_else()

library(dplyr, warn.conflicts = FALSE)
data <- tibble(
Number_X = c(1L, 2L, 1L, 3L, 1L, 2L),
Amount = c(100L, 100L, 100L, 100L, 100L, 100L)
)
data %>% 
mutate(Amount = replace(Amount, Number_X == 1, 50L))
#> # A tibble: 6 x 2
#>   Number_X Amount
#>      <int>  <int>
#> 1        1     50
#> 2        2    100
#> 3        1     50
#> 4        3    100
#> 5        1     50
#> 6        2    100
data %>% 
mutate(Amount = if_else(Number_X == 1, 50L, Amount))
#> # A tibble: 6 x 2
#>   Number_X Amount
#>      <int>  <int>
#> 1        1     50
#> 2        2    100
#> 3        1     50
#> 4        3    100
#> 5        1     50
#> 6        2    100

创建于2022-02-04由reprex包(v2.0.1(

提示:使用dput()与您的数据更容易共享:

dput(data)
#> structure(list(Number_X = c(1L, 2L, 1L, 3L, 1L, 2L), Amount = c(100L, 
#> 100L, 100L, 100L, 100L, 100L)), class = c("tbl_df", "tbl", "data.frame"
#> ), row.names = c(NA, -6L))

如果您想要tidyverse方法:

data %>%
mutate(Amount = ifelse(Number_X == 1, 50, Amount))

如果你想要data.table的速度和dplyr的语法,你可以考虑dtplyr

最新更新