简体   繁体   中英

t test in a data frame in R using mutate

I am struggling to compute a t-test between 2 groups in data frame in R. The sample code below produces a data frame with 2 columns: Variable and Value. There are 2 variables: "M" and "F".

data <- data.frame(variable = c("M", "F", "F"), value = c(10,5,6))

I need to show that the value for M and F are statistically different from each other. In other words, 10 is statistically different from the mean of 5 and 6. I need to add another column in this data frame that shows the p value. When I run the code below, it gives the following error:

result <- data %>% mutate(newcolumn = t.test(value~variable))

Error in t.test.default(x = c(5, 6), y = 10) : not enough 'y' observations

I don't understand the question.

The test itself could be run as a one sample t test for the mean. It would be

t.test(x = c(5, 6) - 10)

If you want to test running a package dplyr pipe:

library(dplyr)

fun_t_test <- function(x){
  tryCatch(t.test(x)$p.value, error = function(e) NA)
}

data %>%
  mutate(newvalue = value - mean(value[variable == "M"])) %>%
  group_by(variable) %>%
  summarise(p.value = fun_t_test(newvalue))
## A tibble: 2 x 2
#  variable p.value
#  <fct>      <dbl>
#1 F         0.0704
#2 M        NA    

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM