I'm trying to compute a mean on my data but I'm struggling with 2 things: 1. getting the right layout and 2. including the missing values in the outcome.
#My input data:
Stock <- c("A", "A", "A", "A", "A", "A", "B", "B", "B", "B", "B", "B")
Soil <- c("Blank", "Blank", "Control", "Control", "Clay", "Clay", "Blank", "Blank", "Control", "Control", "Clay", "Clay")
Nitrogen <- c(NA, NA, 0, 0, 20, 20, NA, NA, 0, 0, 20, 20)
Respiration <- c(112, 113, 124, 126, 139, 137, 109, 111, 122, 124, 134, 136)
d <- as.data.frame(cbind(Stock, Soil, Nitrogen, Respiration))
#The outcome I'd like to get:
Stockr <- c("A", "A", "A", "B", "B", "B")
Soilr <- c("Blank", "Control", "Clay", "Blank", "Control", "Clay")
Nitrogenr <- c(NA, 0, 20, NA, 0, 20)
Respirationr <- c(111, 125, 138, 110, 123, 135)
result <- as.data.frame(cbind(Stockr, Soilr, Nitrogenr, Respirationr))
Many thanks in advance for your help!
Here's a solution with ddply from the plyr package:
library(plyr)
ddply(d, .(Stock, Soil, Nitrogen), summarise,
Respiration = mean(as.numeric(as.character(Respiration))))
# Stock Soil Nitrogen Respiration
# 1 A Blank <NA> 112.5
# 2 A Clay 20 138.0
# 3 A Control 0 125.0
# 4 B Blank <NA> 110.0
# 5 B Clay 20 135.0
# 6 B Control 0 123.0
Please note that cbind is not a good way to create a data frame. You should use data.frame(Stock, Soil, Nitrogen, Respiration) instead. Due to your approach, all columns of d are factors. I used as.numeric(as.character(Respiration)) to obtain the numeric values of this column.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With