0

When I calculate row means foreach dataset in a list, I want that the name of this new variable (avg) differs for each element of the list, e.g., something like avg_df1, avg_df2, or it takes a part of the dataset name and declares it as a variable name. Can it be done by using the "paste" function?

list = list(df1, df2)

list = lapply(list, function(x){
   x$avg = rowMeans(x[,-2])                
   x 
})
Adam
  • 4,445
  • 1
  • 31
  • 49
Anton
  • 5
  • 2
  • Please supply a [reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) – Val Jun 14 '17 at 14:44

1 Answers1

0

If your input list is named:

> input <- list(df1 = head(mtcars), df2 = tail(mtcars))
> sapply(input, function(x) rowMeans(x[, -2]))
                  df1     df2
Mazda RX4         32.2980 26.8570
Mazda RX4 Wag     32.3795 26.9683
Datsun 710        25.5580 66.2690
Hornet 4 Drive    42.0135 37.3590
Hornet Sportabout 58.2310 68.6710
Valiant           37.9540 28.4890
shosaco
  • 5,915
  • 1
  • 30
  • 48
  • thanks! it works. It gives me row means but the first two columns disappear, when i save the results: data = sapply(input, function(x) rowMeans(x[,-2])). In my datasets, the first two columns provides coordinates. How can i do this while keeping first columns. – Anton Jun 15 '17 at 06:50
  • Just bind the cols together with `cbind(original_data, rowMean_Data)` : `cbind(head(mtcars[, 1:2]), sapply(input, function(x) rowMeans(x[, -2])))` – shosaco Jun 15 '17 at 12:51