首页 > 解决方案 > 在 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() 调用中执行吗?

标签: rdplyr

解决方案


d %>%
  mutate(across(!contains("point"), ~round(as.numeric(.x), 2)))

推荐阅读