我有两个数据帧,具有相同数量的匹配列和行。例如:
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到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中的值(即状态名称)的同时。有人能帮我吗?!
发布于 2018-09-27 13:24:15
对于相同大小的数据帧(),可以很好地定义元素级算法.因此,可以方便地计算百分比变化。
## remove `col1` as it is not numeric
100 * (df.2017[-1] - df.2010[-1]) / df.2010[-1]以下内容将col1添加回
data.frame(df.2017[1], 100 * (df.2017[-1] - df.2010[-1]) / df.2010[-1])https://stackoverflow.com/questions/52538012
复制相似问题