rnorouzian
rnorouzian

Reputation: 7517

sapply() misbehaving in R

I'm trying to have R substitute c(1/2, 1, sqrt(2)/2 ) for rscale = argument using sapply(). But I'm wondering why I'm getting 3 same answers (should get 3 different answers)?

ttype = 1 
t = -.742
N1 = 102
N2 = ifelse(ttype==1, NA, 102)

rscale = sqrt(2)/2
tl = 1     
dexp = -1  

library(BayesFactor)

Gi1 <- ttest.tstat(t, N1, ifelse(ttype==1, F, N2),nullInterval = 
c(ifelse(dexp==-1, -Inf, Inf), ifelse(tl==1, 0, Inf)),rscale = rscale, simple = TRUE)

UrUr <- sapply(c(1/2, 1, sqrt(2)/2 ), function(rscale) Gi1 )## HERE I get 3 same answers!

Upvotes: 0

Views: 67

Answers (2)

detroyejr
detroyejr

Reputation: 1154

Agreed with the previous answers. You can also try using sapply like this:

    sapply(c(1/2, 1, sqrt(2)/2), function(x) ttest.tstat(t, N1, ifelse(ttype==1, F, N2),nullInterval = c(ifelse(dexp==-1, -Inf, Inf), ifelse(tl==1, 0, Inf)),rscale = x, simple = TRUE))

Sapply will then cycle through your vector using the parameter "x" as a placeholder for each element in your vector c.

Upvotes: 1

be_green
be_green

Reputation: 753

As @HubertL said, Gi1 is a number, not a function. You need to write a function that takes in a parameter and calculates the ttest.tstat on it, plugging the new variable into the "rscale" parameter. For example,

library(BayesFactor)

Gi1 <- function(x) {
 ttest.tstat(t, N1, ifelse(ttype==1, F, N2),
 nullInterval = c(ifelse(dexp==-1, -Inf, Inf), 
 ifelse(tl==1, 0, Inf)),rscale = x, simple = TRUE) }

UrUr <- sapply(c(1/2, 1, sqrt(2)/2 ), Gi1)
UrUr

And you should get three different answers.

Upvotes: 2

Related Questions