gpt4 book ai didi

r - 两个数据框之间的逐元素百分比变化

转载 作者:行者123 更新时间:2023-12-01 23:37:13 26 4
gpt4 key购买 nike

我有 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.2010df.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 中的值(即州名)时。谁能帮帮我?!

最佳答案

对于相同大小的数据帧,逐元素算法是明确定义的。因此可以方便地计算百分比变化

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

关于r - 两个数据框之间的逐元素百分比变化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52538012/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com