gpt4 book ai didi

r - 如何使用R中的应用函数组来计算带有加号分隔符的值的平均值

转载 作者:行者123 更新时间:2023-12-04 12:18:44 26 4
gpt4 key购买 nike

我有这样的数据

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")

我想用+进行字符串分割并获取单元格内值的平均值。我的代码对一列执行此操作 sapply(strsplit(as.character(tt$WT_H20), "\\+"), function(x)mean(as.numeric(x))) ,但我想使用 apply 函数组对所有列执行此操作。我可以使用循环来做到这一点,但想使用应用函数。

最佳答案

lapply 循环遍历tt 的列。 grepl 检查列是否有 "+"。如果是,则在 "+" 处拆分,转换为数字,并取平均值。

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

关于r - 如何使用R中的应用函数组来计算带有加号分隔符的值的平均值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55422861/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com