两个数据帧之间按元素的百分比变化 [英] element-wise percentage change between two data frames

查看:66
本文介绍了两个数据帧之间按元素的百分比变化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有2个数据帧,具有相等数量的匹配列和行。例如:

I have 2 data frames with equal number of matching columns and rows. For example:

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 每个值。

I need to create a new data frame with percent change from df.2010 to df.2017 for each value.

预期结果:

                  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 中的值的同时(即州名)。有人可以帮我吗?!

I've done some research on the *apply function family as well as for loops, but I'm not familiar enough with R to get to where I need to be! Especially while preserving the values in col1 (i.e. State names). Can anybody help me?!

推荐答案

对于大小相同的数据帧,元素定义的算术定义明确。因此,可以方便地从

Element-wise arithmetic is well-defined for data frames of the same size. So the percentage change can be conveniently computed from

## 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])

这篇关于两个数据帧之间按元素的百分比变化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆