Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
293 views
in Technique[技术] by (71.8m points)

How to calculate a ratio for each month in a year and attach 12 ratio columns (will be 12 columns) to the origianl dataset in R?

My dataset has 3000 observations (rows) and 24 variables (columns). First 12 (column 1 to 12) variables are price value from January to December in a year. The remaining 12 variables (column 13 to 24) are rent value from January to December in the same year. I would like to caculate the price/rent for each month and add the 12 new ratios columns to the end of my origianl dataset. How can I do this in R?

Thank you in advance!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You could do :

df[paste0('ratio', 1:12)] <- df[1:12]/df[13:24]

This will create 12 new columns called ratio1, ratio2 ... ratio12. where ratio1 is column1/column13 ratio2 is column2/column14 and so on.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...