Assigning content of a R dataFrame cell based on some conditions -
this question has answer here:
i have r dataframe df 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 add column compute average current if serial number , year same serial number , years. have 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
for (i in unique(df$serial_n)) { (j in unique (df$year)) { data=subset(df,serial_n==i & year==j) df$average<-mean(data$current) } }
when run it, have following error
error in `$<-.data.frame`(`*tmp*`, "average", value = nan) : replacement has 1 row, data has 0
what problem? how can fix it?
we can use data.table
. convert 'data.frame' 'data.table' (setdt(df)
), grouped 'serialn', , 'year', mean
of 'current' , assign new column 'average'.
library(data.table) setdt(df)[, average := mean(current) ,.(serialn, year)]
Comments
Post a Comment