I have
df1 <- data.frame (ID = c("A01", "B01", "C03"), meta=LETTERS[1:3])
df2 <- data.frame (C03 = c(15,25,35), A01 = c(10,20,30), B01 = c(20,20,30))
I need to attach to each level of ID in df1 the colSums information for this level in df2.
i know a very basic way to do this, but there must be much better ways to do this:
vec1 <- as.data.frame(colSums(df2))
vec1$ID <- row.names(vec1)
df.m <- merge(df1, vec1, by ="ID")
df.m ### desired output
ID meta colSums(df2)
1 A01 A 60
2 B01 B 70
3 C03 C 75
Thank you!
We can use
df1$Sum <- colSums(df2)[df1$ID]
-output
> df1
ID meta Sum
1 A01 A 60
2 B01 B 70
3 C03 C 75
Another way with match:
df1$Sum <- colSums(df2)[match(df1$ID, names(colSums(df2)))]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With