简体   繁体   中英

R loop on data frame

I am working on a data frame which I named 'data'

I need to calculate the weighted mean age for each study, that is to say for each row. I can use the following set of functions:

weighted.mean(x=data[1,7:8],w=data[1,5:6]) weighted.mean(x=data[1,7:8],w=data[1,5:6]) weighted.mean(x=data[2,7:8],w=data[2,5:6]) weighted.mean(x=data[3,7:8],w=data[3,5:6]) weighted.mean(x=data[4,7:8],w=data[4,5:6]) weighted.mean(x=data[5,7:8],w=data[5,5:6]) weighted.mean(x=data[6,7:8],w=data[6,5:6])

Is it possible to create some kind of loop so that I don't have to write six commands but just one and then attach the results as a new column in my data frame ? Many thanks for your help

As Gregor as pointed out, it's very basic, and you should try to find answers in the help manual and hundreds of tutorials available on online. Anyway, this should help you.

 for(i in 1:7) {
    weighted.mean(x=data[i,7:8],w=data[i,5:6])
 }

People usually downvote questions without proper research. Better do some homework next time. All the best.

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