TDo
TDo

Reputation: 744

Add one row in a data frame to all rows of another data frame

I have 2 data frames:

A <- data.frame(x = c(1,4), y = c(3,5))
B <- data.frame(x = c(3,6), y = c(7,9))

A

x   y
1   3
4   5

B

x    y
2    4
3    6

I want to add all rows in A to the first row of B. My desired output data frame is:

x    y
3    7
6    9

I tried B[1, ] + A but it did not work:

#Error in Ops.data.frame(A, B[1, ]) : 
#  ‘+’ only defined for equally-sized data frames

Really appreciate any help!

Upvotes: 2

Views: 569

Answers (2)

akrun
akrun

Reputation: 887128

We can also replicate the first row of 'B' and add with 'A'

unlist(B[1,])[col(A)] + A
#  x y
#1 3 7
#2 6 9

Upvotes: 2

Zheyuan Li
Zheyuan Li

Reputation: 73315

Without converting everything into matrix and working with matrix, we can use:

mapply("+", A, B[1, ])

Another way (more similar to using matrices), is:

A + B[rep.int(1, nrow(A)),]

Upvotes: 4

Related Questions