首页 > 解决方案 > 使用 mutate 和 replace 进行舍入 - dplyr

问题描述

我有以下数据:

library(dplyr)

d <- data_frame(
region = c('all', 'nj', 'rkl', 'all'),
place = c("one", "two","three", "four"),
figures= c(5, 7, 4, 8),
figures2 = c(3, 5, 6, 7))

我想在 dplyr 中使用mutateandreplace来舍入一些行,而不是其他行。所以这是我的代码:

d %>%
  mutate(figures = replace(figures, region == 'all' & place !='two', 
round(d$figures/10)*10)) %>% 
  mutate(figures2 = replace(figures2, region == 'all' & place !='one', 
round(d$figures/10)*10)) -> d2

这实际上做了我想要它做的事情。但是我收到以下警告消息In x[list] <- values :number of items to replace is not a multiple of replacement length。我通常会忽略这一点,因为代码正在做我想做的事情。但是,当将代码应用于更大的数据集时,四舍五入会停止工作,正如我所期望的那样。

有谁知道这可能是为什么?

谢谢

标签: rdplyrrounding

解决方案


您实际尝试做的事情是更好地包裹在 an 中if_else而不是 using replace

d %>%
  mutate(figures = if_else(region == 'all' & place !='two', round(figures/10)*10, figures), 
         figures2 = if_else(region == 'all' & place !='one', round(figures/10)*10, figures2))

# A tibble: 4 x 4
#   region place figures figures2
#   <chr>  <chr>   <dbl>    <dbl>
# 1 all    one         0        3
# 2 nj     two         7        5
# 3 rkl    three       4        6
# 4 all    four       10       10

replace(x, list, values)类似于x[list] <- values,但不改变x自身。因此,它创建了一个向量,其中xat 索引的值list被替换为values。因此它期望listvalues的长度相等。如果没有,它们将被回收。

在您的情况下,现在让我们仔细看看第一个替换,因为第二个替换具有基本相同的问题。虽然起初看起来这两个向量 (region == 'all' & place !='two'round(figures/10)*10) 的长度相同,但实际上它们不仅仅是count的两个TRUE值。region == 'all' & place !='two'因此,您会收到警告消息,因为您尝试使用四个值 ( round(figures/10)*10) 来替换两个值。


推荐阅读