Aggregating a dataframe dynamically with column names in strings from another dataframe

后端 未结 2 1758
遇见更好的自我
遇见更好的自我 2021-01-25 15:44

Ok, so I have a configuration dataframe that will specify, how I want to aggregate a few columns in another dataframe.

config frame:

conf <- rbind(            


        
相关标签:
2条回答
  • 2021-01-25 15:57

    This looks easier to me (after correcting your sinful ways):

    dd <- data.frame( c("a1", "a1", "a1"), c("b1", "b1", "b2"), c(1, 2, 3))
    names(dd) <- c("a", "b", "cnt")
    
    aggregate(dd$cnt , dd[ as.character(conf[, 1]) ], sum)
    #--------
       a  b x
    1 a1 b1 3
    2 a1 b2 3
    
    0 讨论(0)
  • 2021-01-25 16:10

    Stealing @Justin's suggestion here's what I ended up doing.

    aggregate(as.formula(paste("cnt", 
                               paste(conf[,1], collapse=" + "), 
                               sep=" ~ ")), data=dd, sum)
    
    0 讨论(0)
提交回复
热议问题