user11009316
user11009316

Reputation:

how to multiply each row with a scaler in corresponding column?

I have this data, the last column is 1 and -1 . I want to multiply each row with coresponding last column element (1 or -1).

    col1.   col2.  col3.   col4
      3       2     4        1
      4        3    8        -1
      2        3     4       1 
      3         4     1       -1

output:

    col1.   col2.  col3.   col4
      3        2      4         1
      -4        -3    -8        -1
      2         3      4        1 
      -3         -4     -1       -1

Upvotes: 0

Views: 35

Answers (1)

www
www

Reputation: 39154

Here is one way. We can use mutate_at and specify the column to multiply as follows.

library(dplyr)

dat2 <- dat %>% mutate_at(vars(-col4), list(~ . * col4))
dat2
#   col1. col2. col3. col4
# 1     3     2     4    1
# 2    -4    -3    -8   -1
# 3     2     3     4    1
# 4    -3    -4    -1   -1

Data

dat <- read.table(text = "col1.   col2.  col3.   col4
      3       2     4        1
      4        3    8        -1
      2        3     4       1 
      3         4     1       -1",
                  header = TRUE)

Upvotes: 1

Related Questions