0

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

FcmC
  • 143
  • 9
  • 4
    Sure, have a look at `help("for")` or the [section on for loops in An Introduction to R](https://cran.r-project.org/doc/manuals/r-release/R-intro.html#Repetitive-execution). Then try it out. Maybe look at [similar questions on Stack Overflow](http://stackoverflow.com/q/38429826/903061). Come here and ask a question when you've tried and gotten stuck - show us your code and we'll help fix it. Don't come here before trying expecting a custom introduction and tutorial. Such basic questions are actually impossible to answer well without seeing attempt because it's not clear what you don't know. – Gregor Thomas Jan 27 '17 at 23:22

1 Answers1

0

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.