使用 tidyverse 转换一组反引号列的 class?

Convert class of a group of backticked columns using the tidyverse?

如何使用 tidyverse 转换一组反引号列的 class?

这里,数据框 sumtbl 包含临床试验患者 Bil​​l 和 Ted 的实验室测试结果,反引号列的 class 是因素。我使用 tidyr spread 函数将实验室结果从长转换为宽。我在此示例中使用 as.character,因为在现实世界中,我的结果是存储为字符值的数字。

set.seed(7073)
basetbl <- data.frame(pt  = c("BILL","TED"), 
                      res = as.character(abs(rnorm(10))),
                      day = rep(c(1:5), 2))

sumtbl  <- basetbl %>% 
           group_by(pt) %>%
           spread(key = day, value = res) %>%
           ungroup()

在我尝试的解决方案中,有创建一个带有反引号列名称的字符向量,但随后我使用 mutate_at 会产生评估错误 - 找不到对象。

modcols  <-  sapply(seq(1:tail(colnames(sumtbl), 1)), function(x) paste0('`',x, '`'))

outtbl   <-  sumtbl %>%
             mutate_at(modcols, funs(as.numeric(.)))

我可以直接更改列,但有更好的方法吗?

sumtbl$`1` <- as.numeric(sumtbl$`1`)

以下将起作用。此外,您正在将因子转换为数字,因此必须先将因子转换为字符,然后使用 as.numeric(as.character(.)).

outtbl   <-  sumtbl %>%
  mutate_at(vars(-pt), funs(as.numeric(as.character(.))))

# # A tibble: 2 x 6
#       pt       `1`       `2`        `3`       `4`       `5`
#   <fctr>     <dbl>     <dbl>      <dbl>     <dbl>     <dbl>
# 1   BILL 0.4861669 0.1039447 0.69618180 0.7344558 0.9792622
# 2    TED 1.2097490 0.6166524 0.01480253 0.9925388 1.0973267

我们可以使用 names 到 select 列

sumtbl %>%
     mutate_at(names(.)[-1],  funs(as.numeric(as.character(.))))
# A tibble: 2 x 6
#     pt       `1`       `2`        `3`       `4`       `5`
#  <fctr>     <dbl>     <dbl>      <dbl>     <dbl>     <dbl>
#1   BILL 0.4861669 0.1039447 0.69618180 0.7344558 0.9792622
#2    TED 1.2097490 0.6166524 0.01480253 0.9925388 1.0973267

请注意,反引号仅在打印输出中显示。如果我们看 names

names(sumtbl)[-1]
#[1] "1" "2" "3" "4" "5"

因此,'modcols' 将是

modcols <- names(sumtbl)[-1]
sumtbl %>%
     mutate_at(modcols,  funs(as.numeric(as.character(.))))
# A tibble: 2 x 6
#      pt       `1`       `2`        `3`       `4`       `5`
#   <fctr>     <dbl>     <dbl>      <dbl>     <dbl>     <dbl>
#1   BILL 0.4861669 0.1039447 0.69618180 0.7344558 0.9792622
#2    TED 1.2097490 0.6166524 0.01480253 0.9925388 1.0973267

这里不需要用 vars 换行