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
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