I have a data like this
tt<- structure(list(Time = c(48L, 48L, 72L, 72L), WT_H20 = structure(c(13L,
11L, 17L, 14L), .Label = c("0", "0.2+0.2", "0.5+0.4", "0.5+0.6",
"0.8+0.85", "1.2+1.3", "1.3+1.35", "1.5+1.1", "1.5+1.2", "1.6+2",
"1.7+1.5", "1.8+1.5", "1.9+1.7", "1.9+2.1", "2.1+1.7", "2.3+2.7",
"2.8+2.8", "2.9+2.2"), class = "factor"), WT_Ago2_800 = structure(c(1L,
1L, 4L, 5L), .Label = c("0", "0.1+0.1", "0.5+0.1", "0.5+0.5",
"0.8+0.8"), class = "factor"), WT_Ago2_400 = structure(c(14L,
8L, 4L, 15L), .Label = c("0", "0.1+0.1", "0.2+0.2", "0.5+0.5",
"0.6+0.55", "0.7+0.6", "0.75+0.7", "0.8+0.8", "0.9+0.8", "0.9+0.9",
"1.1+1.1", "1.35+1.3", "1.6+1.7", "1+1", "2+2.4"), class = "factor")), row.names = 17:20, class = "data.frame")
I want to string split and get the average of values within cells with+
. I have my code that does this for one column sapply(strsplit(as.character(tt$WT_H20), "\\+"), function(x) mean(as.numeric(x)))
, but I want to do this for all columns using apply group of functions. I can do this with loops, but wanted to use apply functions.
lapply
loops through the columns of tt
. grepl
checks if the columns have "+"
. If it does, split at "+"
, convert to numeric, and take mean.
data.frame(lapply(tt, function(x){
if (any(grepl("\\+", x))){
sapply(strsplit(as.character(x), "\\+"), function(y) mean(as.numeric(y)))
}else{
x
}
}))
# Time WT_H20 WT_Ago2_800 WT_Ago2_400
#1 48 1.8 0.0 1.0
#2 48 1.6 0.0 0.8
#3 72 2.8 0.5 0.5
#4 72 2.0 0.8 2.2
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments