How to do median splits within factor levels in R?

前端 未结 3 1745
有刺的猬
有刺的猬 2021-02-14 16:05

Here I make a new column to indicate whether myData is above or below its median

### MedianSplits based on Whole Data
#create some test data
myDataFrame=data.fra         


        
3条回答
  •  伪装坚强ぢ
    2021-02-14 16:34

    Here is a solution using the plyr package.

    myDataFrame <- data.frame(myData=runif(15),myFactor=rep(c("A","B","C"),5))
    library(plyr)
    ddply(myDataFrame, "myFactor", function(x){
        x$Median <- median(x$myData)
        x$FactorLevelMedianSplit <- factor(x$myData <= x$Median, levels = c(TRUE, FALSE), labels = c("Below", "Above"))
        x
    })
    

提交回复
热议问题