summer
summer

Reputation: 13

calculate average over multiple data frames?

I'd like to calculate the sum over two data.frames. Here is my data.frame U_data

ID    Rating
1     3.4
2     4.5
3     2.1

Here is my second data.frame M_data

M     Rating
M1    3.4
M2    2.9
M3    4.7
M4   5.0

I need to create new data.frame avg_data that add with corresponding data in above data.frame and minus 1. For example, for ID 1, M2, 3.4+ 2.9-1= 5.3.

ID    M1    M2    M3    M4
1     5.8   5.3  7.1   7.4
2
3                          

Can anyone help me with this problem?

Upvotes: 0

Views: 72

Answers (2)

Rick
Rick

Reputation: 898

# Does this work for you?
df1 <- data.frame(ID = 1:3, Rating = c(3.4, 4.5, 2.1))
df2 <- data.frame(M = c("M1", "M2", "M3", "M4"), Rating = c(3.4, 2.9, 4.7, 5.0))
answer <- outer(df1$Rating, df2$Rating, "+")
answer <- answer -1
colnames(answer) <- df2$M
rownames(answer) <- df1$ID
answer

Upvotes: 1

DatamineR
DatamineR

Reputation: 9618

Try this (assuming your U_data is df1 and M_data is df2):

res <- t(sapply(df1[,2], function(x) x + df2[,2]-1))
colnames(res) <- df2[,1]
data.frame(ID = df1[,1], res)
  ID  M1  M2  M3  M4
1  1 5.8 5.3 7.1 7.4
2  2 6.9 6.4 8.2 8.5
3  3 4.5 4.0 5.8 6.1

Upvotes: 0

Related Questions