0

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
  • Pretty sure this is a duplicate as it is just a multiplication essentially - `dat[-ncol(dat)] <- dat[-ncol(dat)] * dat[[ncol(dat)]]` – thelatemail Aug 15 '19 at 22:35
  • Possible duplicate of https://stackoverflow.com/questions/43189087/multiply-each-column-of-a-data-frame-by-the-corresponding-value-of-a-vector – thelatemail Aug 15 '19 at 22:37

1 Answers1

1

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)
www
  • 38,575
  • 12
  • 48
  • 84
  • 1
    Also, base R `dat[-4] <- dat[-4] *dat[,4]` – akrun Aug 15 '19 at 22:59
  • 1
    @akrun Thanks for sharing. Base R is more concise in this case. – www Aug 15 '19 at 23:00
  • @akrun I couldn't get your method –  Aug 15 '19 at 23:10
  • 2
    Try this: `dat[, -4] <- dat[, -4] * dat[, 4]`. And next time, please be more specific about your data type in your question. – www Aug 15 '19 at 23:15
  • Looking your question again, I noticed your question tagged as `dataframe`. This is why people including me assume you are working on a data frame in the begining. – www Aug 15 '19 at 23:18