1

I am new to coding and am having trouble with this problem. Here is a simplified version of my dataset:

Plot x1 x2 x3
1    1  1  2  3
2    1  3  4  5
3    2  4  5  6
4    2  6  7  8
5    3  7  8  9
6    3  9 10 11

I want to make a new dataset where the data is grouped by 'Plot' and each column has the average value for that column's plot. For this example, I would want to take the above dataset and create a dataset like the following:

 Plot x1 x2 x3
1    1  2  3  4
2    2  5  6  7
3    3  8  9 10

I usually use code that looks like this when I am averaging:

require(dplyr)

dataAvg <- data %>%
  dplyr::group_by(Plot) %>%
  dplyr::summarise(meanx1=mean(x1))
dataAvg

However, the issue here is that I would need to specify each column that gets averaged. My actual dataset has a large number of columns to be averaged, so this does not work.

Any help would be hugely appreciated. I realize that this is likely a somewhat simple question, but I was not able to find an answer by using the search function on Stack Overflow. Please let me know if I can provide any other information for further clarity. Thanks so much for your time.

Tom
  • 377
  • 3
  • 13
  • 1
    `aggregate(.~Plot, data, mean)` – Onyambu Mar 16 '22 at 20:14
  • `data %>% group_by(Plot) %>% summarize(across(everything(), mean))` – Onyambu Mar 16 '22 at 20:15
  • here is the solution, where you can see if the row was averaged: `data <- data %>% group_by(Plot) %>% mutate(averaged = length(x1)) %>% summarise_all(mean) %>% mutate(averaged = ifelse(averaged == 1, FALSE, TRUE))` – Bloxx Mar 16 '22 at 20:24

2 Answers2

1

you need to use dplyr::summarise_all function, which aggreagate each of the column at once. There is a summarise_if which is helpful if you want to apply it to e.g. only numeric variables.

data <- read.table(text = "Plot x1 x2 x3
1    1  1  2  3
2    1  3  4  5
3    2  4  5  6
4    2  6  7  8
5    3  7  8  9
6    3  9 10 11", header = T)

library(dplyr)

data %>% group_by(Plot) %>% summarise_all(mean)
polkas
  • 3,797
  • 1
  • 12
  • 25
0

collap from the collapse package does this extremely easily:

> collap(dat, ~ Plot)

  Plot x1 x2 x3
1    1  2  3  4
2    2  5  6  7
3    3  8  9 10
George Savva
  • 4,152
  • 1
  • 7
  • 21