2014-11-07 6 views
0

다음 R 데이터 프레임이 있습니다. 최종 "점수"데이터 프레임에서 논리 벡터 그룹별로 요약 통계를 얻으려고합니다.R 요약 합계 논리 벡터 그룹화

#original df 
    type <- c("A", "B", "C","D","E") 
    user <- c('user1','user2','user3','user4','user5') 
    text <-c('this is a tweet','this is a fb post','tweeting is fun','other text','another fb post') 
    tweet.mention <- c('TRUE','FALSE','TRUE','FALSE','FALSE') 
    fb.mention <- c('FALSE','TRUE','FALSE','FALSE','TRUE') 
    df1 <- cbind.data.frame(type, user, text,tweet.mention,fb.mention) 
    df1 

    #Remove records that are all FALSE 
    tweet<-as.logical(tweet.mention) 
    fb<-as.logical(fb.mention) 
    test<-cbind(tweet,fb) 
    true<-rowSums(test) 
    all<-cbind(test,true) 

    #Create score df 
    score<-subset(df1,true>=1) 

    #score API return 
    sentiment<-c(1,.5,2,-2) 

    #scored text 
    score<-cbind(score,sentiment) 

스코어 df는 득점 수치를 포함해야하며 기록 4를 제거합니다. 평균 감정 점수를 얻고 싶지만 트윗 멘트 (1.5)와 fb. 멘션 (- 75)으로 그룹화합니다. 나는 기초 R에서 요약을 시도했지만 그게 전부입니다. 따라서 그룹별로 또는 부분 집합이 필요하다고 생각합니다. 나는 심령 패키지에서 describeBy를 시도했다. 그것도 도움이되지 않습니다.

논리적 벡터의 수를 항상 알 수는 없으므로 열을 지정하고 == TRUE를 사용하여 수동으로 부분 집합을 만들 수는 없습니다. lapply 통해 열 헤더의 목록이나 벡터를 만들 수 있지만 그룹화를 완료하는 코드 또는 함수를 알 수 없습니다.

나는이 답변에 대한 R 요리 책을 확인했을뿐만 아니라 기본 r 및 심술 vignettes도 읽었지만 찾을 수는 없습니다. 크게 도움을 주셔서 감사합니다.

답변

4

2 방법 :

> with(score, tapply(sentiment, list(tweet.mention, fb.mention), mean)) 
     FALSE TRUE 
FALSE NA -0.75 
TRUE 1.5 NA 

과 :

> aggregate(sentiment~tweet.mention+fb.mention, data=score, mean) 
    tweet.mention fb.mention sentiment 
1   TRUE  FALSE  1.50 
2   FALSE  TRUE  -0.75 
1

아래는 data.table 패키지를 사용하는 솔루션입니다. 이를 수행하는 여러 가지 방법이 있습니다.

library(data.table) 
setDT(score) 
score[, mean(sentiment), by = list(tweet.mention, fb.mention)] 

이 그룹에 대한 data.tableby 키워드를 사용합니다. 출력은

tweet.mention fb.mention V1 
1:   TRUE  FALSE 1.50 
2:   FALSE  TRUE -0.75 
+0

너무 감사합니다. 나는 data.table 패키지를 사용하고 탐색 할 것이다. – user1370741

0

dplyr을 사용하는 다른 방법입니다. stringsAsFactors = FALSE을 사용할 수 있습니다. 이 방법으로 모든 변수를 여기에서 만드는 것을 피할 수 있습니다. 기본 R을 사용하여

df1 %>% 
    filter(tweet.mention != FALSE | fb.mention != FALSE) %>% 
    mutate(sentiment = c(1, 0.5, 2, -2)) %>% 
    group_by(tweet.mention, fb.mention) %>% 
    summarize(outcome = mean(sentiment)) 

# tweet.mention fb.mention outcome 
#1   FALSE  TRUE -0.75 
#2   TRUE  FALSE 1.50 

데이터

df1 <-structure(list(type = c("A", "B", "C", "D", "E"), user = c("user1", 
"user2", "user3", "user4", "user5"), text = c("this is a tweet", 
"this is a fb post", "tweeting is fun", "other text", "another fb post" 
), tweet.mention = c("TRUE", "FALSE", "TRUE", "FALSE", "FALSE" 
), fb.mention = c("FALSE", "TRUE", "FALSE", "FALSE", "TRUE")), .Names = c("type", 
"user", "text", "tweet.mention", "fb.mention"), row.names = c(NA, 
-5L), class = "data.frame")