2017-10-07 48 views
0

想知道是否有人有聚合和排除Inf值的解決方案。例如總計不包括inf

df <- data.frame(Id = c(1:9), 
     Fact = c("A", "A", "A", "B", "B", "B", "C", "C", "C"), 
     Values = c(10, 5, 14, 3, 1, 10/0, 7, 11, 22)) 

注意價值爲ID 6是天道酬勤

嘗試此,請注意,對於事實B中的maxvalues將是天道酬勤

maxvalues <- aggregate(Values~Fact,df,max, na.rm=TRUE) 
maxvalues 

想的maxvalues的事實B到是3(這將是不包括Inf的值)。如果可能的話,希望堅持使用base R。

回答

3

使用符合條件的匿名函數上x

aggregate(Values ~ Fact, df, function(x) max(x[x < Inf], na.rm = TRUE)) 
# Fact Values 
# 1 A  14 
# 2 B  3 
# 3 C  22 

或先於聚集刪除這些行:

aggregate(Values ~ Fact, df[df$Values < Inf, ], max, na.rm = TRUE) 
# Fact Values 
# 1 A  14 
# 2 B  3 
# 3 C  22