简体   繁体   中英

Apply function to more than one column in R

I read a few posts about it but still didn't get the answer. It is probably something simple that I'm missing. I have the function

GoodmanKruskalGamma(mydata$item1, mydata$totalscore, conf.level=0.95)

But I'd like to apply it automatically to other columns in my data frame instead of doing manually for every item

GoodmanKruskalGamma(mydata$item1, mydata$totalscore, conf.level=0.95)
GoodmanKruskalGamma(mydata$item2, mydata$totalscore, conf.level=0.95)
GoodmanKruskalGamma(mydata$item3, mydata$totalscore, conf.level=0.95)

Can someone help me how to create a loop? Is there another useful way of doing this?

Thanks!

* SOLVED *

I managed to use this code to find the solution

install.packages("magicfor") #Install Magicfor
library(magicfor) #Load Magicfor package
magic_for(print, silent = TRUE) #Load Magic for
for(coln in c(2:41)) {
  print(GoodmanKruskalGamma(newdata[,coln], newdata$totalscore, conf.level=0.95))
} #Perform loop
results <- magic_result_as_dataframe() #Storage results
results #Show results

* ADDITIONAL QUESTION *

How could I do a code to make the correlations between pairs of columns? For example, between an item and its restscore?

GoodmanKruskalGamma(mydata$item1, mydata$restscore1, conf.level=0.95)
GoodmanKruskalGamma(mydata$item2, mydata$restscore2, conf.level=0.95)

I tried this but didn't work

for(coln in c(2:41)) {
    for(coln2 in c(48:87)) {
  print(GoodmanKruskalGamma(newdata[,coln], newdata[,coln2], conf.level=NA))}  
  } #Perform loop

EDIT : I found the second solution, for those interested

### Calculate Kruskal Gamma between Item and Restscore ###

results3 <- capture.output(
for(coln in c(2:41)) {
  for(restn in c(43:82)) {
  if(coln + 41 == restn){
  print(GoodmanKruskalGamma(newdata[,coln], newdata[,restn], conf.level=NA))
  }else{}
  }
})
for(coln in c('item1', 'item2', 'item3')) {
   GoodmanKruskalGamma(mydata[,coln], mydata$totalscore, conf.level=0.95)
}

should do the trick

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