Reputation: 133
I have created numerous output tables from t-tests and ANOVAs and I'd like to round all numeric columns of the tables apart from the column containing the p-values (p.value).
Current code:
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)
The issue is that this also rounds my p-value which is then displayed as 0. I already have a function for reporting p-values for my markdown file so I'm wondering how I can keep the p-value (p.value) unchanged yet round all other numeric columns to 2 digits?
Thanks
Upvotes: 3
Views: 4437
Reputation: 7457
If you really wanna round all numeric columns but the p.value
column, just make shure your p.value
column doesn't get rounded by coercing it to a character before the rounding and then back to numeric after rounding.
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
If you just want to round some columns, then you probably be better of using mutate_at
as @user5249203 promotes.
Upvotes: 6
Reputation: 4648
You can do simple 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>
Created on 2019-04-18 by the reprex package (v0.2.1)
Upvotes: 2
Reputation: 647
not very nice and not dplyr, but i think it should do the job :)
select all elements from t.test which are numeric and not p.value and apply round to them
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)
Upvotes: 0