0

I've searched a lot to answers about this but so far I'm really struggling. I have 5 data frames, all with 6 rows and 10 columns. I would like to create a new data frame with the same structure and with the means for each position on the 5 data frames. I've tried this:

    age_wealth1 <- data.frame(age_wealth1)
    age_wealth2 <- data.frame(age_wealth2)
    age_wealth3 <- data.frame(age_wealth3)
    age_wealth4 <- data.frame(age_wealth4)
    age_wealth5 <- data.frame(age_wealth5)

age_wealth_total <- matrix(nrow = nrow(age_wealth1), ncol = ncol(age_wealth1))

for(j in 1:nrow(age_wealth_total[j]))
  {
    for(k in 1:ncol(age_wealth_total[k]))
    {
      age_wealth_total[j,k] <- mean(age_wealth1[j,k], age_wealth2[j,k], age_wealth3[j,k], age_wealth4[j,k], age_wealth5[j,k])
    }
}

The loop gives error about the columns length, saying that is 0, which is not true because

ncol(age_wealth_total) # = 10

I really would like to have more tips about how to iterate over columns and rows in a matrix or a data frame using loops. Thanks a lot!

Jaap
  • 81,064
  • 34
  • 182
  • 193
  • Please read the info about [how to ask a good question](http://stackoverflow.com/help/how-to-ask) and how to give a [reproducible example](http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example/5963610). This will make it much easier for others to help you. – Jaap Feb 26 '18 at 10:39

1 Answers1

1

To get your code to work, you can modify it like this:

age_wealth1 <- data.frame(age_wealth1)
age_wealth2 <- data.frame(age_wealth2)
age_wealth3 <- data.frame(age_wealth3)
age_wealth4 <- data.frame(age_wealth4)
age_wealth5 <- data.frame(age_wealth5)

age_wealth_total <- matrix(nrow = nrow(age_wealth1), ncol = 
ncol(age_wealth1))

for(j in 1:nrow(age_wealth_total))
{
  for(k in 1:ncol(age_wealth_total))
  {
    age_wealth_total[j,k] <- mean(c(age_wealth1[j,k], age_wealth2[j,k], age_wealth3[j,k], age_wealth4[j,k], age_wealth5[j,k]))
  }
}

But in your case you would probably want something easier:

age_wealth_total <- (age_wealth1 + age_wealth2 + age_wealth3 + age_wealth4 + age_wealth4 + age_wealth5) / 5
kluu
  • 2,848
  • 3
  • 15
  • 35