【问题标题】:Replace NA with zero when separating with tidyr?使用 tidyr 分离时将 NA 替换为零?
【发布时间】: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 %&gt;% separate(x, into = c("x1", "x2")) %&gt;% replace_na(list(x2 = 0))

标签: r tidyverse tidyr


【解决方案1】:

我们可以在使用separate函数之前格式化x列。

dat %>% 
  mutate(x = format(x, nsmall = 3)) %>%
  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     0  32.3
# 3  1993   544  33.4

【讨论】:

    猜你喜欢
    • 2022-01-24
    • 1970-01-01
    • 2023-02-23
    • 2018-10-01
    • 2019-11-05
    • 2017-11-27
    • 2019-11-14
    • 2019-05-20
    • 1970-01-01
    相关资源
    最近更新 更多