1

I have a data set like this:

df<-read.table (text=" House1   House2  House3  House 4
9   4   8   3
8   6   3   3
9   9   6   5
8   8   3   9
9   5   5   10
4   3   8   6
3   6   10  3
9   8   6   8
3   9   10  5
7   8   2   4
", header=TRUE)

The values 2,4,3 and 1.5 are multiplied in each row. 2 goes to House1, 4 goes to House2, 3 goes to column3 and 1. goes to House4. This gives me the following table:

House1  House2  House3  House 4
18  16  24  4.5
16  24  9   4.5
18  36  18  7.5
16  32  9   13.5
18  20  15  15
8   12  24  9
6   24  30  4.5
18  32  18  12
6   36  30  7.5
14  32  6   6

is there a simple code to do it?

user330
  • 1,256
  • 1
  • 7
  • 12
  • [Multiply rows of matrix by vector?](https://stackoverflow.com/questions/3643555/multiply-rows-of-matrix-by-vector) – Henrik Jul 21 '20 at 21:21

4 Answers4

2

We can transpose the dataset, mutliply by vector and transpose the output

df[] <- t(t(df) * c(2, 4, 3, 1.5))

Or using sweep

sweep(df,  2, c(2, 4, 3, 1.5), `*`)
akrun
  • 874,273
  • 37
  • 540
  • 662
2

(akrun's sweep is slightly more elegant than this, I believe.)

A data.frame-centric way would be

df2 <- as.data.frame(Map(`*`, df, c(2, 4, 3, 1.5)))
df2
#    House1 House2 House3 House4
# 1      18     16     24    4.5
# 2      16     24      9    4.5
# 3      18     36     18    7.5
# 4      16     32      9   13.5
# 5      18     20     15   15.0
# 6       8     12     24    9.0
# 7       6     24     30    4.5
# 8      18     32     18   12.0
# 9       6     36     30    7.5
# 10     14     32      6    6.0

or, if you're multiplying it in-place, then

df[] <- Map(`*`, df, c(2, 4, 3, 1.5))
r2evans
  • 141,215
  • 6
  • 77
  • 149
1

Another base R option using matrix multiplication:

df[]<-as.matrix(df)%*%diag(c(2, 4, 3, 1.5))

such that

> df
   House1 House2 House3 House4
1      18     16     24    4.5
2      16     24      9    4.5
3      18     36     18    7.5
4      16     32      9   13.5
5      18     20     15   15.0
6       8     12     24    9.0
7       6     24     30    4.5
8      18     32     18   12.0
9       6     36     30    7.5
10     14     32      6    6.0
ThomasIsCoding
  • 96,636
  • 9
  • 24
  • 81
0

Though not as elegant as some other solutions, you can also use apply:

df[] <- t(apply(df, 1, function(x) x*c(2, 4, 3, 1.5)))

Output

> df
   House1 House2 House3 House4
1      18     16     24    4.5
2      16     24      9    4.5
3      18     36     18    7.5
4      16     32      9   13.5
5      18     20     15   15.0
6       8     12     24    9.0
7       6     24     30    4.5
8      18     32     18   12.0
9       6     36     30    7.5
10     14     32      6    6.0
slava-kohut
  • 4,203
  • 1
  • 7
  • 24