在每组中,我想找到两个子组的平均值。需要说明的是,数据如下所示:
Group Val1 Val2 Val3
1 50 0.03 50.1
1 50.2 0.05 50.1
2 50.3 0.01 50.1
1 50 0.03 50.2
1 50.1 0.04 50.2
1 50 0.01 50.3
1 50 0.02 50.3
2 50.3 0.03 50.3
在Val3的每个组中,我想计算第1组中Val2的平均值和第2组中Val2的平均值。在某些情况下,对于Val3,第2组中没有成员。这是我尝试的代码
fileB.mean.dat <- tapply(combined.sorted.data[combined.sorted.data[,1] == 2,3], combined.sorted.data[combined.sorted.data[,1] == 2,4], mean)
我不知道如何在上面的代码中包含检查是否有第2组的成员,如果不是为了使Val 3的平均值为0。换句话说,组应该有代表性的平均值对于Val 3的每个值,1和2。
答案 0 :(得分:3)
您可以使用reshape2
library(reshape2)
dcast(data = aggregate(Val2 ~ Group + Val3, data = df, mean),
formula = Group~Val3,
value.var = "Val2")
# Group 50.1 50.2 50.3
#1 1 0.04 0.035 0.015
#2 2 0.01 NA 0.030
将SymbolixAU's answer的输出转换为您喜欢的内容。
sapply(split(df[c("Group", "Val2")], df$Val3),
function(a) sapply(unique(df$Group),
function(x) setNames(mean(a$Val2[a$Group == x]), x)))
# 50.1 50.2 50.3
#1 0.04 0.035 0.015
#2 0.01 NaN 0.030
或者你也可以在基地R做,但会相对更复杂
df = structure(list(Group = c(1, 1, 5, 1, 1, 1, 1, 5), Val1 = c(50,
50.2, 50.3, 50, 50.1, 50, 50, 50.3), Val2 = c(0.03, 0.05, 0.01,
0.03, 0.04, 0.01, 0.02, 0.03), Val3 = c(50.1, 50.1, 50.1, 50.2,
50.2, 50.3, 50.3, 50.3)), .Names = c("Group", "Val1", "Val2",
"Val3"), row.names = c(NA, -8L), class = "data.frame")
数据强>
val aToSeqOfB: Flow[A, Seq[B], NotUsed] = ...
val bToC: Flow[B, C, NotUsed] = ...
答案 1 :(得分:1)
我们可以使用library(tidyverse)
df %>%
group_by(Group, Val3) %>%
summarise(Val2 = mean(Val2)) %>%
spread(Val3, Val2)
# A tibble: 2 x 4
# Groups: Group [2]
# Group `50.1` `50.2` `50.3`
#* <dbl> <dbl> <dbl> <dbl>
#1 1 0.04 0.035 0.015
#2 2 0.01 NA 0.030
namespace Program
{
class Path
{
private readonly MapLocation[] _path;
public Path(MapLocation[] path)
{
_path = path;
}
}
}