gpt4 book ai didi

r - 如何在不使用 R 中的公式的情况下改变列(部分)

转载 作者:行者123 更新时间:2023-12-04 07:32:33 24 4
gpt4 key购买 nike

我想更换那些 NA在专栏y由矢量 subst <- c(5,6,7) .我的结果出问题了,而且我认为这不是做我想做的事情的正确方法。

library(dplyr)
#>
#> Attaching package: 'dplyr'
#> The following objects are masked from 'package:stats':
#>
#> filter, lag
#> The following objects are masked from 'package:base':
#>
#> intersect, setdiff, setequal, union

df <- tibble(x = c("a", "a", "b", "b", "b", "c", "c"),
y = c(2, 3, NA, NA, NA, 1, 2))


subst <- c(5, 6, 7)

df2 <- df %>% mutate(y = ifelse(x == "b", subst, y))

# But I want to obtain
df3 <- tibble(x = c("a", "a", "b", "b", "b", "c", "c"),
y = c(2, 3, 5, 6, 7, 1, 2))
Created on 2021-06-07 by the reprex package (v2.0.0)

最佳答案

我们可以使用 replace 而不是 ifelse ifelse要求所有参数都相同 length

library(dplyr)
df2 <- df %>%
mutate(y = replace(y, x == 'b', subst))
-输出
df2
df2
# A tibble: 7 x 2
x y
<chr> <dbl>
1 a 2
2 a 3
3 b 5
4 b 6
5 b 7
6 c 1
7 c 2

关于r - 如何在不使用 R 中的公式的情况下改变列(部分),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67877570/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com