gpt4 book ai didi

r - 使用 apply 进行计算

转载 作者:行者123 更新时间:2023-12-02 05:54:41 24 4
gpt4 key购买 nike

我有一张表,其中有五列“年份”、“收入”、“养老金”、“收入”和“工资”。在这张表中,我用下面的代码进行了计算:

library(dplyr)
#DATA
TEST<-data.frame(
Year= c(2000,2001,2002,2003,2004,2005,2006,2007,2008,2009,2010,2011,2012,2013,2014,2015,2016,2017,2018,2019,2020,2021),
Revenue =c(8634,5798,6022,6002,6266,6478,6732,7224,6956,6968,7098,7620,7642,8203,9856,20328,22364,22222,23250,25250,26250,27250),
Pensions =c(8734,5798,7011,7002,7177,7478,7731,7114,7957,7978,7098,7710,7742,8203,9857,10328,11374,12211,13150,15150,17150,17150),
Income =c(8834,5898,6033,6002,6366,6488,6833,8334,6956,6968,8098,8630,8642,8203,9856,30328,33364,32233,33350,35350,36350,38350),
Wages =c(8834,5598,8044,8002,8488,8458,8534,5444,8958,8988,5098,5840,5842,8203,9858,40328,44384,42244,43450,45450,48450,45450)
)

#FUNCTION
fun1 <- function(x){ ((x - lag(x))/lag(x))*100}

#CALCULATION
ESTIMATION_0<-mutate(TEST,
Nominal_growth_Revenue=fun1(Revenue),
Nominal_growth_Pensions=fun1(Pensions),
Nominal_growth_Income=fun1(Income),
Nominal_growth_Wages=fun1(Wages)
)

但我的目的是优化此代码并使用 apply 函数(或类似的函数)进行此计算。也就是说,对于此计算,我编写了 4 行代码,但我喜欢用 1 行代码来完成此操作。那么有人可以帮我解决这个问题吗?

最佳答案

假设您有一个包含相关列的字符向量:

cols <- c("Revenue", "Pensions", "Income", "Wages")

使用apply():

TEST[paste0('nomial_growth', cols)] <- apply(TEST[cols], 2, fun1) 

data.table:

library(data.table)
setDT(TEST)
TEST[, (paste0('nomial_growth', cols)) := lapply(.SD, fun1), .SDcols = cols]

关于r - 使用 apply 进行计算,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54926903/

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