Calculate mean difference per row and per group

前端 未结 2 1894
生来不讨喜
生来不讨喜 2021-01-26 22:46

I have a data.frame with many rows and columns and I want to calculate the mean difference of each value to each of the other values within a group.
Here an exa

2条回答
  •  青春惊慌失措
    2021-01-26 23:46

    Here's a solution using only base R:

    myData <- data.frame(ID=c(1,1,1,2,2,2,2), value=c(4,5,7,8,6,5,6), diff=NA)
    for(i in 1:nrow(myData))
        myData$diff[i] <- with(data = myData,
            sum((value[i] - value[ID==ID[i]])**2)/length(value[ID==ID[i]]))
    
    myData
    
      ID value     diff
    1  1     4 3.333333
    2  1     5 1.666667
    3  1     7 4.333333
    4  2     8 4.250000
    5  2     6 1.250000
    6  2     5 2.750000
    7  2     6 1.250000
    

提交回复
热议问题