我有 2 个数据框,它们具有相同数量的匹配列和行。例如:
df.2010 <- data.frame(col1 = c("Connecticut", "Delaware", "District of Columbia", "Florida", "Georgia"), col2 = 10, col3 = 20, col4 = 30)
df.2017 <- data.frame(col1 = c("Connecticut", "Delaware", "District of Columbia", "Florida", "Georgia"), col2 = 20, col3 = 25, col4 = 90)
df.2010
col1 col2 col3 col4
1 Connecticut 10 20 30
2 Delaware 10 20 30
3 District of Columbia 10 20 30
4 Florida 10 20 30
5 Georgia 10 20 30
df.2017
col1 col2 col3 col4
1 Connecticut 20 25 90
2 Delaware 20 25 90
3 District of Columbia 20 25 90
4 Florida 20 25 90
5 Georgia 20 25 90
我需要创建一个新的数据框,其百分比变化来自df.2010
to df.2017
对于每个值。
预期结果:
col1 col2 col3 col4
1 Connecticut 100 25 200
2 Delaware 100 25 200
3 District of Columbia 100 25 200
4 Florida 100 25 200
5 Georgia 100 25 200
概念函数是:
# args:
# x: original amount
# y: new amount
percent.change <- function(x,y) {
((y-x)/x)*100
}
我已经做了一些研究*apply
函数族以及for
循环,但我对 R 不够熟悉,无法到达我需要的地方!特别是在保留价值的同时col1
(即国家名称)。有谁能够帮助我?!