1

I have a data.frame called d on which I would like to make the following operation

d <- mutate(d,netto_0 = netto_0_pc * tot_pop)
d <- mutate(d,netto_1 = netto_1_pc * tot_pop)
d <- mutate(d,netto_2 = netto_2_pc * tot_pop)
d <- mutate(d,netto_3 = netto_3_pc * tot_pop)
d <- mutate(d,netto_4 = netto_4_pc * tot_pop)
d <- mutate(d,netto_5 = netto_5_pc * tot_pop)
d <- mutate(d,netto_6 = netto_6_pc * tot_pop)
d <- mutate(d,netto_7 = netto_7_pc * tot_pop)
d <- mutate(d,netto_8 = netto_8_pc * tot_pop)
d <- mutate(d,netto_9 = netto_9_pc * tot_pop)

I'd like to achieve this result in a more efficient way by performing a for-loop. Unfortunately variable names are not character strings, therefore the following code does not work.

for( k in 0:9 ){
  newcol <- paste0( 'netto_', k )
  oldcol <- paste0( 'netto_', k, '_pc' )
  d <- mutate(d, newcol = oldcol * tot_pop)
}

Or also

for( k in 0:9 ){
  newcol <- paste0( 'netto_', k )
  oldcol <- paste0( 'netto_', k, '_pc' )
  d$newcol < d$oldcol * d$tot_pop
}

How can I fix it?

ExaFusion
  • 11
  • 1
  • 3
  • This should work: `d[paste0("netto_", 0:9)] <- d[paste0("netto_", 0:9, "_pc")] * d$tot_pop`, if not, please share a reproducible example. – markus Oct 02 '18 at 10:32
  • Thank you very much @markus this actually works. I tried something very similar in a for-loop and I have no idea why it didn't work at that time. However this is only the last of many times I needed to do a for loop on variable names, therefore this solution only solves partially my problem. Is there any way to switch from character to variable name? – ExaFusion Oct 02 '18 at 11:23
  • 3
    This is hard / impossible to tell without a [reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example). – markus Oct 02 '18 at 11:42
  • 2
    It would be really helpful if you could provide a reproducible example to see how your data is actually structured as this might affect the solution quite substantially. E.g. it would be very useful to know if there are other columns present in your data. – roming Oct 02 '18 at 11:45
  • 3
    Read `help('$')`. If you construct column names dynamically, you must use `[` (or `[[`) for subsetting. – Roland Oct 02 '18 at 11:57

0 Answers0