【发布时间】:2018-11-08 02:17:41
【问题描述】:
我在小数点中有一列小数,我想将其分成整数和非整数分量。如果小数点后的部分正好为零,则separate() 函数将其转换为NA。
library("tidyverse") # or
# library("tibble")
# library("tidyr")
x <- c(1992.345, 1993.000, 1993.544)
y <- c(31.2, 32.3, 33.4)
dat <- tibble(x, y)
dat %>%
separate(x,
into = c("x1", "x2"),
convert = TRUE,
fill = "right")
#> # A tibble: 3 x 3
#> x1 x2 y
#> <int> <int> <dbl>
#> 1 1992 345 31.2
#> 2 1993 NA 32.3
#> 3 1993 544 33.4
我想告诉separate() 保留零而不是用NA 替换它?我知道我可以mutate() 和replace_na(),例如
dat %>%
separate(x,
into = c("x1", "x2"),
convert = TRUE,
fill = "right") %>%
mutate(x2 = replace_na(x2, 0))
#> # A tibble: 3 x 3
#> x1 x2 y
#> <int> <dbl> <dbl>
#> 1 1992 345 31.2
#> 2 1993 0 32.3
#> 3 1993 544 33.4
问题:我可以跳过mutate() 步骤并在separate() 步骤中将NA 替换为零吗?或者,这是否尽可能简洁?我愿意接受其他解决方案。
由reprex package (v0.2.1) 于 2018 年 11 月 7 日创建
【问题讨论】:
-
你可以通过不使用
mutate使replace_na更简洁一点:dat %>% separate(x, into = c("x1", "x2")) %>% replace_na(list(x2 = 0))