How do I create a loop and/or a function to divide 200 columns (and create 200 new columns/variables) by another column to get a percentage?
How do I do this in a loop so I can do 200 columns? and how do I name the name the columns so that it is the old column name with a "p_" in front of it? Is this possible?
For example I'm trying to do something like this but with 200 columns.
fans <- data.frame(
population = c(1234, 5678, 2345, 6789, 3456, 7890,
4567, 8901, 5678, 9012, 6789),
bearsfans = c(123, 234, 345, 456, 567,678, 789, 890, 901, 135, 246),
packersfans = c(11,22,33,44,55,66,77,88,99,100,122),
vikingsfans = c(39, 49, 59, 61, 32, 22, 31, 92, 52, 10, 122))
print(fans)
attach(fans)
## create new columns which are the ratio of fans to population
fans$p_bearsfan = bearsfans/population
print(fans)
Output:
## population bearsfans packersfans vikingsfans p_bearsfan
## 1 1234 123 11 39 0.09967585
## 2 5678 234 22 49 0.04121169