Home > other >  multiply number of rows that have specefic value in a column
multiply number of rows that have specefic value in a column

Time:04-07

I have data that contain some rows and columns like this for example

     col1   col2   col3   col4
r1   A      1      1       2
r2   B      3      1       2
r3   A      4      1       2
r4   D     10      1       2
r5   E     12      1       2
r6   A     5       1       2

i want to multiply by specefic value (three for example) the rows that have value A or B in col1

so the result will be

     col1   col2   col3   col4
r1   A      3      3       6
r2   B      9      3       6
r3   A     12      3       6
r4   D     10      1       2
r5   E     12      1       2
r6   A     15      3       6

Thank you

CodePudding user response:

You can simply do,

df[df$col1 == 'A', -1] <- df[df$col1 == 'A', -1] * 3

CodePudding user response:

data.table solution

library(data.table)
DT <- fread("col1   col2   col3   col4
   A      1      1       2
   B      3      1       2
   A      4      1       2
   D     10      1       2
   E     12      1       2
   A     5       1       2")

cols <- names(DT)[-1]
DT[col1 == "A", (cols) := lapply(.SD, `*`, 3), .SDcols = cols][]

#    col1 col2 col3 col4
# 1:    A    3    3    6
# 2:    B    3    1    2
# 3:    A   12    3    6
# 4:    D   10    1    2
# 5:    E   12    1    2
# 6:    A   15    3    6

CodePudding user response:

1) dplyr We can use across in dplyr or replace the first argument to across with where(is.numeric) :

library(dplyr)

DF %>% mutate(across(-col1, ~ ifelse(col1 %in% c("A", "B"), 3 * ., .)))

giving:

  col1 col2 col3 col4
1    A    3    3    6
2    B    9    3    6
3    A   12    3    6
4    D   10    1    2
5    E   12    1    2
6    A   15    3    6

2) collapse Alternatively use ftransformv in the collapse package.

library(collapse)

ftransformv(DF, is.numeric, \(x) ifelse(DF$col1 %in% c("A", "B"), 3*x, x))

Note

Lines <- "col1   col2   col3   col4
   A      1      1       2
   B      3      1       2
   A      4      1       2
   D     10      1       2
   E     12      1       2
   A     5       1       2"
DF <- read.table(text = Lines, header = TRUE)
  • Related