r - 在 dplyr 1.0.0 的单个 mutate() 函数中组合两个列转换
问题描述
我需要首先使用 mutate 将字符列的子集转换为数字列,然后将这些数字列四舍五入到小数点后两位。
这是一些玩具数据。
library(dplyr)
# dataset made up of all character columns
d <- data.frame(point = c("point = 1", "point = 2", "point = 3"),
b = as.character(c(1.0004, 3.4567, 4.6789)),
c = as.character(c(10.231, 11.345, 18.987)),
stringsAsFactors = F)
str(d)
# 'data.frame': 3 obs. of 3 variables:
# $ point: chr "point = 1" "point = 2" "point = 3"
# $ b : chr "1.0004" "3.4567" "4.6789"
# $ c : chr "10.231" "11.345" "18.987"
现在我们可以使用 mutate 将最后两列转换为数字
d %>%
mutate(across(!contains("point"), as.numeric)) -> d2
str(d2)
# 'data.frame': 3 obs. of 3 variables:
# $ point: chr "point = 1" "point = 2" "point = 3"
# $ b : num 1 3.46 4.68
# $ c : num 10.2 11.3 19
现在将最近转换的数字列四舍五入到小数点后两位
d2 %>% mutate(across(where(is.numeric), round, 2))
# point b c
# 1 point = 1 1.00 10.23
# 2 point = 2 3.46 11.35
# 3 point = 3 4.68 18.99
我想知道的是这两个转换可以在单个 mutate() 调用中执行吗?
解决方案
d %>%
mutate(across(!contains("point"), ~round(as.numeric(.x), 2)))
推荐阅读
- matlab - 如何连接向量形成矩阵并用零填充
- c# - 如果经过身份验证的用户属于指定角色,为什么授权角色属性会拒绝访问?
- javascript - ASP.NET MVC 如何在 javascript 中获取选定对象的某些字段?
- c# - 如何处理无法访问的 ADFS 元数据
- java - 如何从主类调用一个方法到另一个活动
- php - 不同数组中键的值
- javascript - 来自 JSON 的 DOM 表
- webrtc - WebRTC replaceTrack,getStats不返回audioInputLevel
- javascript - document.getElementsByName("q1").disabled = true 不工作
- javascript - 即使单击标签区域,引导程序默认表单输入也会打开。我该如何防止这种情况?