How to use a function or expression in dplyr mutate on the attributes of a templ...
source link: https://www.codesd.com/item/how-to-use-a-function-or-expression-in-dplyr-mutate-on-the-attributes-of-a-template-t-test-created-by-formula-call-inside-dplyr-do.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
How to use a function or expression in dplyr mutate on the attributes of a template t.test created by formula call inside dplyr do?
library(dplyr)
mtcars %>%
group_by(vs) %>%
do(tt=t.test(mpg~am, data=.)) %>%
mutate(t=tt$statistic, p=tt$p.value)
I have performed t.test on mgp with respect to am for each vs. I am trying to extract the attributes of the t.test model and arrange them in a data frame. I am able to extract p-value and t-value or any one-length attribute.
Output:
Source: local data frame [2 x 4]
Groups: <by row>
vs tt t p
1 0 <S3:htest> -2.579484 0.034481482
2 1 <S3:htest> -3.764735 0.004436935
Now, if I want to extract the mean group difference using the code below:
mtcars %>%
group_by(vs) %>%
do(tt=t.test(mpg~am, data=.)) %>%
mutate(t=tt$statistic, p=tt$p.value, delta=diff(tt$estimate))
or even when I just want to access the mean of group 0
mutate(t=tt$statistic, p=tt$p.value, delta=tt$estimate[0])
R throws the error below:
Error: object 'tt' not found
It seems tt is evaluated in a different environment where it is not defined when an expression or function is applied on it. I tried using funs too but no success. Could somebody please shed some light here?
We could extract it within the do
without using any additional package.
mtcars %>%
group_by(vs) %>%
do({
tt=t.test(mpg~am, data=.)
data.frame(t=tt$statistic, p=tt$p.value,delta=diff(tt$estimate))
})
# vs t p delta
# (dbl) (dbl) (dbl) (dbl)
#1 0 -2.579484 0.034481482 4.700000
#2 1 -3.764735 0.004436935 7.628571
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK