Complicated reshaping

后端 未结 8 1470
南方客
南方客 2020-12-25 14:01

I want to reshape my dataframe from long to wide format and I loose some data that I\'d like to keep. For the following example:

df <- data.frame(Par1 =          


        
8条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-25 14:42

    Trying to wrap different aggregation expressions into a self-contained function (expressions should yield atomic values)...

    multi.by <- function(X, INDEX,...) {
        expressions <- substitute(...())
        duplicates <- duplicated(INDEX)
        res <- do.call(rbind,sapply(split(X,cumsum(!duplicates),drop=T), function(part) 
            sapply(expressions,eval,part,simplify=F),simplify=F))
        if (is.data.frame(INDEX)) res <- cbind(INDEX[!duplicates,],res)
        else rownames(res) <- INDEX[!duplicates]
        res
    }
    
    multi.by(df,df[,1:2],
        pre=mean(Val[Type=="pre"]), 
        post=mean(Val[Type=="post"]),
        Num.pre=sum(Type=="pre"),
        Num.post=sum(Type=="post"),
        ParD=paste(ParD, collapse="_"))
    

提交回复
热议问题