Home > OS >  How to loop over several rows multiplicating with a constant number in R?
How to loop over several rows multiplicating with a constant number in R?

Time:04-09

I have a problem coding the following task:

gene constant value Value A Value B Value C Value D
ABCD 0.5224 123 456 789 123
EFGH 0.556 254 267 2334 12334
IJKL 0.7226 23423 56345 67867 17534
MNOP 0.0001 2423 143 1554 1344

Given this table I want to multiply every value with the constant value of the row, so in the end the code should calculate this:

gene constant value Value A Value B Value C Value D
ABCD 0.5224 123 * 0.5224 456 * 0.5224 789 * 0.5224 123 * 0.5224
EFGH 0.556 254 * 0.556 267 * 0.556 2334 * 0.556 12334 * 0.556
IJKL 0.7226 23423 * 0.7226 56345 * 0.7226 67867 * 0.7226 17534 * 0.7226
MNOP 0.0001 2423 * 0.0001 143 * 0.0001 1554 * 0.0001 1344 * 0.0001

Can anyone help how to implement this in R programming language?

Kind regards,
Hashriama

CodePudding user response:

Another possible solution, based on base R:

(I have just noticed that @Sotos had, in a comment, suggested something very similar; therefore, I am going to remove my answer.)

df[-(1:2)] <-  df$constant.value * df[-(1:2)]
df

#>   gene constant.value    Value.A    Value.B    Value.C    Value.D
#> 1 ABCD         0.5224    64.2552   238.2144   412.1736    64.2552
#> 2 EFGH         0.5560   141.2240   148.4520  1297.7040  6857.7040
#> 3 IJKL         0.7226 16925.4598 40714.8970 49040.6942 12670.0684
#> 4 MNOP         0.0001     0.2423     0.0143     0.1554     0.1344

CodePudding user response:

Using the dplyr package, you can use the across() helper function to apply the same operation across multiple columns that starts_with "Value".

library(dplyr)

# dplyr approach
df %>% mutate(across(starts_with("Value"), ~.x * `constant value`))

# or similarly in base R
df[, grepl("Value", colnames(df))] <- df[, grepl("Value", colnames(df))] * df$`constant value`

  gene constant value    Value A    Value B    Value C    Value D
1 ABCD         0.5224    64.2552   238.2144   412.1736    64.2552
2 EFGH         0.5560   141.2240   148.4520  1297.7040  6857.7040
3 IJKL         0.7226 16925.4598 40714.8970 49040.6942 12670.0684
4 MNOP         0.0001     0.2423     0.0143     0.1554     0.1344

Input data

df <- read.table(header = T, sep = "\t", check.names = F, text = "
gene    constant value  Value A Value B Value C Value D
ABCD    0.5224  123 456 789 123
EFGH    0.556   254 267 2334    12334
IJKL    0.7226  23423   56345   67867   17534
MNOP    0.0001  2423    143 1554    1344")
  • Related