舍入所有数字列,但在表中

问题描述 投票:1回答:3

我已经从t检验和ANOVA创建了许多输出表,我想要除了包含p值(p.value)的列之外,对表的所有数字列进行舍入。

当前代码:

library(dplyr)
library(broom)

a <- rnorm(100, 0.75, 0.1)

t.test <- t.test(a, mu = 0.5, alternative = "greater") %>%
          broom::tidy() %>%
          mutate_if(is.numeric, round, 2)

问题是,这也会使我的p值四舍五入,然后显示为0.我已经有一个报告我的降价文件的p值的函数,所以我想知道如何保持p值(p.value)未更改但将所有其他数字列舍入为2位数?

谢谢

r dplyr
3个回答
4
投票

如果你真的想要围绕所有数字列而不是p.value列,那么只需要使你的p.value列不会通过在舍入之前将其强制转换为字符然后在舍入后返回数字而得到舍入。

library(dplyr)
library(broom)

a <- rnorm(100, 0.75, 0.1)

t.test <- t.test(a, mu = 0.5, alternative = "greater") %>%
  broom::tidy() %>%
  mutate(p.value = as.character(p.value)) %>%
  mutate_if(is.numeric, round, 2) %>%
  mutate(p.value = as.numeric(p.value))
t.test
# A tibble: 1 x 8
  estimate statistic  p.value parameter conf.low conf.high method            alternative
     <dbl>     <dbl>    <dbl>     <dbl>    <dbl>     <dbl> <chr>             <chr>      
1     0.76      28.3 1.52e-49        99     0.74       Inf One Sample t-test greater    

如果你只想围绕一些列,那么你可能更好地使用mutate_at作为@ user5249203提升。


1
投票

你可以做简单的mutate_at

library(dplyr)
library(broom)

a <- rnorm(100, 0.75, 0.1)
t.test(a, mu = 0.5, alternative = "greater") %>%
  broom::tidy() %>% 
  mutate_at(vars(- c(p.value,method,alternative)), round, 2)

#> # A tibble: 1 x 8
#>   estimate statistic  p.value parameter conf.low conf.high method
#>      <dbl>     <dbl>    <dbl>     <dbl>    <dbl>     <dbl> <chr> 
#> 1     0.75      27.1 5.89e-48        99     0.74       Inf One S~
#> # ... with 1 more variable: alternative <chr>

reprex package创建于2019-04-18(v0.2.1)


0
投票

不是很好,不是dplyr,但我认为它应该做的工作:)

选择t.test中的所有元素,这些元素是数字而不是p.value,并应用于它们

t.test[(names(t.test)[which(!names(t.test) %in% c("p.value")  & sapply(t.test, class) == "numeric")])] = 
  lapply(t.test[(names(t.test)[which(!names(t.test) %in% c("p.value")  & sapply(t.test, class) == "numeric")])], round, 2)
© www.soinside.com 2019 - 2024. All rights reserved.