2017-10-06 13 views
1

monthprecip의 각 요일이 기록 된 예제 데이터 프레임이 있습니다. 각 부분 집합에 대한 각 서브 세트 내의 배포판에 대해 조건부로 합계 값 사용

set.seed(560) 
df<-data.frame(month= rep(1:4, each=30), 
      precip= rep(c(rnorm(30, 20, 10), rnorm(30, 10, 2), 
      rnorm(30, 50, 1), rnorm(30, 15, 3)))) 

, 나는 그 달의 precip 값의 평균 위 또는 아래 값은 +/- 2 표준 편차 (SD)이었다 인스턴스의 수를 계산하고 싶습니다. 본질적으로 가치 분포의 극단 (즉, 분포의 꼬리)에서 가치를 발견했다. 이 결과 열은 count입니다. 35.969 전술 한 달 값

set.seed(560) 
output<-data.frame(month= rep(1:4, each=1), count= c(1,2,1,1)) 

통지하고 2.61 이하의 값이 +/- 평균의 2SD 내에있다 :이 예시적인 세트에 대해 다음과 같이

출력이 나타나는 것이다. 하나의 값 (강수 = 41.1)은이 요구 사항에 부합합니다. 증명 :

sub1<- subset(df, month==1) 
    v1<- mean(sub1$precip)+ 2*sd(sub1$precip)#35.969 
    v2<- mean(sub1$precip)- 2*sd(sub1$precip)#2.61 
sub2<- subset(df, month==2) 
v3<- mean(sub2$precip)+ 2*sd(sub2$precip)#13.89 
v4<- mean(sub2$precip)- 2*sd(sub2$precip)#7.35 
sub3<- subset(df, month==3) 
v5<- mean(sub3$precip)+ 2*sd(sub3$precip)#51.83 
v6<- mean(sub3$precip)- 2*sd(sub3$precip)#48.308 
sub4<- subset(df, month==4) 
v7<- mean(sub4$precip)+ 2*sd(sub4$precip)#18.69 
v8<- mean(sub4$precip)- 2*sd(sub4$precip)#9.39 

나는 시도했다 :

output<- 
df %>% 
group_by(month)%>% 
summarise(count= sum(precip > (mean(precip)+(2*sd(precip)))& 
         precip < (mean(precip)-(2*sd(precip)))))) 

답변

0

기본 R에서

tapply(df$precip, df$month, function(a) sum(abs(scale(a)) >= 2)) 

출력

1 2 3 4 
1 2 2 1 
1

아주 간단한 수정으로 또는 | 로직 및 & 변경 에이 두 행에 행이 없습니다.

output<- 
    df %>% 
    group_by(month)%>% 
    summarise(count= sum(precip > (mean(precip)+(2*sd(precip))) | 
         precip < (mean(precip)-(2*sd(precip))))) 

output 
# A tibble: 4 x 2 
# month count 
# <int> <int> 
# 1  1  1 
# 2  2  2 
# 3  3  2 
# 4  4  1 

그리고

ave, ifelseaggregate로 ( dplyr::group_by()에 대응)를 사용 by베이스 R 용액 대안

do.call(rbind, 
     by(df, df$month, FUN=function(i){ 
      tmp <- i[i$precip < mean(i$precip) - 2*sd(i$precip) | 
        i$precip > mean(i$precip) + 2*sd(i$precip),] 

      return(data.frame(month=i$month[[1]], count=nrow(tmp))) 
      }) 
     ) 

# month count 
# 1  1  1 
# 2  2  2 
# 3  3  2 
# 4  4  1 

을 추가 :

df$count <- ifelse(df$precip > ave(df$precip, df$month, FUN=function(g) mean(g) + 2*sd(g)) | 
        df$precip < ave(df$precip, df$month, FUN=function(g) mean(g) - 2*sd(g)), 1, 0) 

aggregate(count ~ month, df, FUN=sum) 

# month count 
# 1  1  1 
# 2  2  2 
# 3  3  2 
# 4  4  1