r - 使用 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 中使用mutate
andreplace
来舍入一些行,而不是其他行。所以这是我的代码:
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
。我通常会忽略这一点,因为代码正在做我想做的事情。但是,当将代码应用于更大的数据集时,四舍五入会停止工作,正如我所期望的那样。
有谁知道这可能是为什么?
谢谢
解决方案
您实际尝试做的事情是更好地包裹在 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
自身。因此,它创建了一个向量,其中x
at 索引的值list
被替换为values
。因此它期望list
和values
的长度相等。如果没有,它们将被回收。
在您的情况下,现在让我们仔细看看第一个替换,因为第二个替换具有基本相同的问题。虽然起初看起来这两个向量 (region == 'all' & place !='two'
和round(figures/10)*10
) 的长度相同,但实际上它们不仅仅是count的两个TRUE
值。region == 'all' & place !='two'
因此,您会收到警告消息,因为您尝试使用四个值 ( round(figures/10)*10
) 来替换两个值。
推荐阅读
- data-migration - 将项目以及历史记录和依赖项从 PTC 完整性 11.0 迁移到 11.2 版本
- swift - 弱捕获方法
- excel - 如何将页码添加到固定标题单元格(没有页眉/页脚)?
- javascript - 滑块显示单个图像
- python - 为什么我得到 TypeError: '<' not supported between 'int' 和 'tuple' 的实例?
- curl - 代理服务中的端点 URL 地址无效
- c++ - 如何在 C++ 中挂起程序然后“取消挂起”它
- mysql - 无法在chrome浏览器、js文件中调用mysql代码
- swift - 有没有办法减少启动集合视图单元格的拖动所需的时间(长按)?
- python-3.x - 如何在将自定义数据集上传到 colab 期间修复错误?