[R] multiplication by groups
Giorgio Garziano
giorgio.garziano at ericsson.com
Sun Apr 24 20:30:07 CEST 2016
df1 <- data.frame(ID = c(1,1,2,2,3,3,4,4,5,5),
A = c(1,0,5,1,1,NA,0,3,2,7),
B = c(2,3,NA,3,4,NA,1,0,5,NA))
df2 <- data.frame(ID = c(1,2,3,4,5),
A = c(1,6,1,3,9),
B = c(5,3,4,1,5))
m <- match(df1$ID, df2$ID)
sel <- c("A", "B")
for (i in 1:nrow(df1)) {
df1[i,sel] <- round(df1[i,sel]/df2[m[i],sel], 2)
}
> df1
ID A B
1 1 1.00 0.4
2 1 0.00 0.6
3 2 0.83 NA
4 2 0.17 1.0
5 3 1.00 1.0
6 3 NA NA
7 4 0.00 1.0
8 4 1.00 0.0
9 5 0.22 1.0
10 5 0.78 NA
>
--
Best,
GG
[[alternative HTML version deleted]]
More information about the R-help
mailing list