Reputation: 23
I am trying to run an AUDPC analysis on some data. The data needs to be split into treatments and replicate blocks for the analysis. Below I have tried to write a function with the aim of spliting the data analyzing and ending up with the output of all treatment-blocks in one table/object
library("agricolae")
library("plyr")
library("dplyr")
data = read.csv("Bio2018.csv", header = TRUE, sep = ",")
data$Treatment = as.character(data$Treatment)
data$Block = as.character(data$Block)
data$Time = as.numeric(data$Time)
AUDPC.rel = function(Treatment, Block){
data.Treatment <- subset(data, data$Treatment == Treatment & data$Block == Block)
AUDPC = data.frame(audpc(data.Treatment$Foci, data.Treatment$Time, type = "absolute"))
}
variables = expand.grid(Treatment = c(unique(data$Treatment)), Block = c(unique(data$Block)))
Relative.AUDPC = mdply(variables,AUDPC.rel)
Relative.AUDPC
The output always give the same number for all treatment-blocks. As shown:
Treatment - Block - evaluation
Non-treated - Rep.1 - 200;
Emerald - Rep.1 - 200;
Nortica - Rep.1 - 200;
Non-treated - Rep.2 - 200;
Emerald - Rep.2 - 200;
Nortica - Rep.2 - 200;
Non-treated - Rep.3 - 200;
Emerald - Rep.3 - 200;
Nortica - Rep.3 - 200;
Upvotes: 2
Views: 228
Reputation: 107652
Consider base R's by
to subset a data frame by one or more factors such as Treatment and Block. And because by
will return a list of data frames (output of function), run do.call
to row bind all df elements to one final data frame.
Also, since by
runs across multiple factors to split across all possible combinations, wrap a tryCatch
for such special subset cases of zero rows that may raise an error of audpc
call.
# BUILD FUNCTION TO RECEIVE SUBSET DF
AUDPC.rel <- function(sub) {
tryCatch(data.frame(Treatment = sub$Treatment[[1]],
Block = sub$Block[[1]],
Evaluation = audpc(sub$Foci, sub$Time, type = "absolute")),
error = function(e)
data.frame(Treatment = sub$Treatment[[1]],
Block = sub$Block[[1]],
Evaluation = NA)
)
}
# CALL BY(), PASSING SUBSETS TO DEFINED FUNCTION
df_list <- by(data, data[c("Treatment", "Block")], AUDPC.rel)
# BUILD SINGLE FINAL DF
final_df <- do.call(rbind, df_list)
Upvotes: 1