Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding a column to a dataframe based on aggregated data in another dataframe

Tags:

merge

dataframe

r

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!

like image 677
nouse Avatar asked Sep 12 '26 19:09

nouse


2 Answers

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
like image 135
akrun Avatar answered Sep 14 '26 15:09

akrun


Another way with match:

df1$Sum <- colSums(df2)[match(df1$ID, names(colSums(df2)))]
like image 43
Maël Avatar answered Sep 14 '26 15:09

Maël



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!