I'm quite new to R and I would like to learn how to write a Loop to create and process several columns.
I imported a table into R that cointains data with 23 variables. For all of these variables I want to calculate the per capita valuem multiply this with 1000 and either write the data into a new table or in the same table as the old data.
So to this for only one column my operation looked like this:
<i>agriculture<-cbind(agriculture,"Total_value_per_capita"=agriculture$Total/agriculture$Total.Population*1000)</i>
Now I'm asking how to do this in a Loop for the 23 variables so that I won't have to write 23 similar lines of code.
I think the solution might look quite similar to the code pasted in this thread:
loop to create several matrix in R (maybe using paste)
but I dind't got it working on my code.
So any suggestion would be very helpful.
cbindinside a loop. If your table's 23 variables are in 23 columns, just loop over the column number rather than label. E.g.,cbind(agriculture, agriculture$Total/agriculture[,j]*1000)wherejis the loop index.agriculture<-cbind(agriculture, "Total_value_per_capita"=agriculture[,24]/agriculture$Total.Population*100but it dindt work out. There was only one new column build with some strange numbers (I think maybe the product of all values over the prevoius columns...)