【问题标题】:R round correlate function from corrr package来自 corrr 包的 R 轮相关函数
【发布时间】:2021-05-16 17:36:45
【问题描述】:

我正在使用 corrr 包中的 correlate 函数创建一个关联表。这是我的代码和输出的屏幕截图。

correlation_table <- corrr::correlate(salary_professor_dataset_cor_table, 
                                      method = "pearson")
correlation_table

我认为如果我可以对相关表中的值进行四舍五入,这会更好看,也更容易阅读。我试过这段代码:

correlation_table <- round(corrr::correlate(salary_professor_dataset_cor_table, 
                                      method = "pearson"),2)

但我收到此错误:

Math.data.frame 中的错误(list(term = c("prof_rank_factor", "yrs.since.phd", : 数据框中的非数字变量:term

此错误消息中的非数字变量部分对我来说没有意义。当我查看结构时,我只看到整数或数字变量类型。

'data.frame':   397 obs. of  6 variables:
 $ prof_rank_factor : num  3 3 1 3 3 2 3 3 3 3 ...
 $ yrs.since.phd    : int  19 20 4 45 40 6 30 45 21 18 ...
 $ yrs.service      : int  18 16 3 39 41 6 23 45 20 18 ...
 $ salary           : num  139750 173200 79750 115000 141500 ...
 $ sex_factor       : num  1 1 1 1 1 1 1 1 1 2 ...
 $ discipline_factor: num  2 2 2 2 2 2 2 2 2 2 ...

如何清理这个带有四舍五入值的相关表?

【问题讨论】:

  • 不知道您是否在脚本顶部尝试过options(digits=2)?
  • 嗨 Manoj,这也是 TarJae 在下面的回答。但我不知道 options(digits=2) 在做什么?它看起来像它的挂代码。这是对更全球化环境的指示吗?
  • 你是对的。 options() 设置和配置全局设置。因此,使用options(digits=2) 意味着您将数字设置为四舍五入到小数点后两位。您可以通过在命令提示符中键入 ?options 来阅读 options() 以调用它的帮助。

标签: r pearson-correlation


【解决方案1】:

使用correlate 返回tibble 输出后,循环across numeric 和round 列

library(dplyr)
corrr::correlate(salary_professor_dataset_cor_table, 
                                  method = "pearson") %>%
    mutate(across(where(is.numeric), round, digits = 2))

【讨论】:

  • 这个给了我一条我不明白的错误消息:/错误:mutate() 输入问题..1。 x 数学函数的非数字参数 ℹ 输入 ..1 是 (function (.cols = everything(), .fns = NULL, ..., .names = NULL) ...。运行rlang::last_error() 以查看错误发生的位置。
  • 谢谢,我现在知道发生了什么。而不是 mutate(across(everything() 它是 mutate(across(where(is.numeric)
  • @hachiko 我之前认为所有列都是数字的。对此感到抱歉
【解决方案2】:

我们可以使用:

options(digits=2)
correlation_table <- corrr::correlate(salary_professor_dataset_cor_table, 
                                      method = "pearson")
correlation_table

【讨论】:

  • 你能帮我理解那些 options(digits=2) 的作用吗?它看起来像它的挂代码。这是对更全球化环境的指示吗?
  • 允许用户设置和检查各种影响 R 计算和显示结果的方式的全局选项。见?options
猜你喜欢
  • 2013-03-03
  • 2020-03-11
  • 2017-09-03
  • 1970-01-01
  • 1970-01-01
  • 2017-03-26
  • 1970-01-01
  • 2018-07-26
  • 2015-09-27
相关资源
最近更新 更多