I have a R DataFrame df with the following content:
Serial N year current
B 10 14
B 10 16
C 12 11
D 40 20
B 11 15
C 12 9
I would like to add a column which compute the average current if serial number and the year are the same serial number and years. I would like to have something like this
Serial N year current Average
B 10 14 15
B 10 16 15
C 12 13 12
D 40 20 20
B 11 15 15
C 12 11 12
I wrote this
for (i in unique(df$Serial_N))
{
for (j in unique (df$year))
{ data=subset(df,Serial_N==i & year==j)
df$Average<-mean(data$current)
}
}
When I run it, I have the following error
Error in `$<-.data.frame`(`*tmp*`, "Average", value = NaN) :
replacement has 1 row, data has 0
What is problem? How can I fix it?