0

I would like to loop through v1 to v3 and dividing them by weight column, but I have issues in the loop (in real life the variables have different names)


Name <- c("Jon", "Bill", "Maria", "Ben", "Tina")
v1 <- c(23, 41, 32, 58, 26)
v2 <- c(13, 41, 35, 18, 66)
v3 <- c(3,34, 33, 34, 23)
weight <- c(2, 4, 3, 5, 6)


df <- data.frame(Name,v1,v2,v3,weight)

print (df)


for(i in 2:4 (df)) {       # for-loop over columns
  df[ , i] <- df[ , i] /df$weight
}
zx8754
  • 52,746
  • 12
  • 114
  • 209
progster
  • 877
  • 3
  • 15
  • 27

1 Answers1

0

A better solution would be to avoid (explicit) loops altogether. Here's a tidyverse solution using across:

library(tidyverse)

df <- data.frame(Name,v1,v2,v3,weight)
df %>% mutate(across(starts_with("v"), function(x) x / weight))
   Name        v1       v2        v3 weight
1   Jon 11.500000  6.50000  1.500000      2
2  Bill 10.250000 10.25000  8.500000      4
3 Maria 10.666667 11.66667 11.000000      3
4   Ben 11.600000  3.60000  6.800000      5
5  Tina  4.333333 11.00000  3.833333      6
Limey
  • 10,234
  • 2
  • 12
  • 32
  • thanks but in real life the variables have different names, so I could not use across – progster Oct 26 '21 at 07:19
  • There are ways of using across with different variable names. If naming is an important feature of the problem, you should include it in your MRE. As an aside, replacing `starts_with("v")` with `-c(Name, weight)` in my solution produces the same result. – Limey Oct 26 '21 at 07:20