gpt4 book ai didi

r - 使用 tidyverse 转换一组反引号列的类?

转载 作者:行者123 更新时间:2023-12-01 15:20:10 25 4
gpt4 key购买 nike

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

这里,数据框 sumtbl 包含临床试验患者 Bil​​l 和 Ted 的实验室测试结果,反引号列的类别是 factor。我使用 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()

basetbl data frame with random numbers for the res column

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

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

enter image description here

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

enter image description here

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

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

关于r - 使用 tidyverse 转换一组反引号列的类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47404609/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com