baz
baz

Reputation: 7117

Doing a loop in R

I need to do a loop (which I haven't done before) and given the observations (column 1), I need to work out (i) which of the combinations across the variables (s1-s5) are significant (P<0.05), (ii) to only keep the combinations that are significant across the variables with the corresponding p values. I thought that this would be a good way to learn how to do a loop in R. The original data is large and is similar to this one:

ob <- c(120,100,85,56,87)
s1 <- c("ab","aa","ab","aa","bb")
s2 <- c("aa","aa","ab","bb","bb")
s3 <- c("bb","ab","aa","ab","ab")
s4 <- c("aa","ab","bb","ab","aa")
s5 <- c("bb","ab","aa","ab","bb")
dset <- data.frame(ob,s1,s2,s3,s4,s5)

dset

ob s1 s2 s3 s4 s5
120 ab aa bb aa bb
100 aa aa ab ab ab
85 ab ab aa bb aa
56 aa bb ab ab ab
87 bb bb ab aa bb

Any help would be appreciated!

Baz

Upvotes: 1

Views: 628

Answers (1)

Chase
Chase

Reputation: 69151

Maybe I'm missing something, but I'm not seeing how it makes sense to add a column of p-values in your data.frame without transposing the data.frame. How do you know which p-value corresponds to which independent variable if they are in different columns? Here's one approach using a for-loop to run the anova's for each independent variable and store them on a new vector:

#Use grep to return the columns that match the pattern "s". This returns their column index. 
#This is what we'll use in the for loop
vars <- grep("s", names(dset))

#Create a new vector to hold the anova results and name it
dat <- vector("integer", length = ncol(dset))
names(dat) <- colnames(dset)

#Run for loop, assigning the p-value from the anova to the proper spot in the vector we made
for (var in vars) {
  dat[var] <- anova(lm(ob ~ dset[, var], data = dset))$"Pr(>F)"[1]
}

All of the above will yield:

> dat
       ob        s1        s2        s3        s4        s5 
0.0000000 0.7219532 0.3108441 0.4668372 0.6908916 0.6908916

I'll leave it up to you as to how you want to relate that back to the original data.frame.

Upvotes: 1

Related Questions