The problem with the code you have is the line:
df$value <- df$value / dfa[dfa$n==df$n,][[1]]
The line dfa$n==df$n returns a logical vector of length max(length(df),length(dfa) , which tells you about each index if n matches. I don't think you can use this to match dfa$n - df$n .
Using base functions, you can use aggregate and merge :
dfa <- aggregate(x=df$value, by=list(df$n), FUN=sum) names(dfa) <- c("n","sum.value") df2 <- merge(df,dfa,by="n",all = TRUE) df2$value2 <- df2$value/df2$sum.value
source share