Apply a function to dataframe subsetted by all possible combinations of categorical variables

后端 未结 4 1052
野的像风
野的像风 2021-01-20 03:30

An example dataframe with categorical variables catA, catB, and catC. Obs is some observed value.

catA <- rep(factor(c(\"a\",\"b\",\"c\")), length.out=10         


        
4条回答
  •  攒了一身酷
    2021-01-20 03:59

    ans <- with(dat, tapply(obs, list(catA, catB, catC), mean))
    ans <- data.frame(expand.grid(dimnames(ans)), results=c(ans))
    names(ans)[1:3] <- names(dat)[1:3]
    
    str(ans)
    # 'data.frame':  36 obs. of  4 variables:
    #  $ catA   : Factor w/ 3 levels "a","b","c": 1 2 3 1 2 3 1 2 3 1 ...
    #  $ catB   : Factor w/ 4 levels "1","2","3","4": 1 1 1 2 2 2 3 3 3 4 ...
    #  $ catC   : Factor w/ 3 levels "d","e","f": 1 1 1 1 1 1 1 1 1 1 ...
    #  $ results: num  69.7 NA NA 55.3 NA ...
    

提交回复
热议问题