0

I have following data:

set.seed(10)
len =100
vnum=rnorm(len)
vint=sample(1:10,len,replace=TRUE)
vbin=sample(letters[1:2],len,replace=TRUE)
dd = data.frame(vnum, vint, vbin)
head(dd)
head(dd)
          vnum vint vbin
1:  0.01874617    3    a
2: -0.18425254    6    a
3: -1.37133055    7    a
4: -0.59916772    9    b
5:  0.29454513    2    b
6:  0.38979430    7    b

I need to compare vnum grouped by vbin by t.test. I also need to do the same with vint and get output as follows: Output needed:

        mean_a  sd_a  mean_b  sd_b  ttest_p.value
vnum
vint

I tried:

aggregate(vnum~vbin, dd, function(x) mean(x) )
  vbin       vnum
1    a -0.1390285
2    b -0.1339682

t(aggregate(vnum~vbin, dd, mean ))
     [,1]         [,2]        
vbin "a"          "b"         
vnum "-0.1390285" "-0.1339682"

But cannot get all functions in one output.

1 Answer 1

1

Define your own function to produce the output that you want:

myt <- function(x, y, data) {
  z <- t.test(y ~ x, data)
  x <- as.character(substitute(x))
  y <- as.character(substitute(y))
  c(mean_a = z$estimate[1], 
    sd_a = sd(dd[[y]][dd[[x]]=="a"]), 
    mean_b = z$estimate[2], 
    sd_b = sd(dd[[y]][dd[[x]]=="b"]), 
    test_p.value = z$p.value)
}

Then you can run it for every variable that you need:

rbind(myt(vbin, vnum, dd), myt(vbin, vint, dd))
##      mean_a.mean in group a      sd_a mean_b.mean in group b     sd_b test_p.value
## [1,]             -0.1390285 0.8427401             -0.1339682 1.042787    0.9788149
## [2,]              6.4509804 2.8587670              5.7551020 3.003683    0.2385821
Sign up to request clarification or add additional context in comments.

2 Comments

@rnso Sorry, had a little typo. Fixed now.
It seems to be working. Only if the mean column title could be reduced from "mean_a.mean in group a" to just "mean_a". Also I need to attach the real dataframe since individual column names need to be accessible. There is also missing values problem and na.rm=T needs to be added somewhere. Thanks for your time.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.