R语言折现求和公式批量计算报错求助:非数值参数问题
问题
我是R语言新手,需要计算特定折现求和公式:对t=22至65的每个t,计算1/(1+r)^(t-22)*W并求和得到单一结果。现有带haven标签的t(年龄)和W(收入均值)数据,自行编写函数并使用apply调用时,出现报错:Error in t - 22 : non-numeric argument to binary operator,同时不确定函数逻辑是否符合需求,寻求解决方法。
样本数据
数据预览:
t W <int+lbl> <dbl> 1 18 4301. 2 19 7721. 3 20 11525. 4 21 13878. 5 22 15954. 6 23 18342. 7 24 19432. 8 25 21647. 9 26 22132. 10 27 23492.
dput构造的可复现数据:
structure(list(t = structure(18:22, labels = c(`Less than 1 year old` = 0L, `90 (90+ in 1980 and 1990)` = 90L, `100 (100+ in 1960-1970)` = 100L, `112 (112+ in the 1980 internal data)` = 112L, `115 (115+ in the 1990 internal data)` = 115L ), label = "Age", var_desc = "AGE reports the person's age in years as of the last birthday. Please see the Comparability section regarding a known Universe issue with AGE and AGEORIG which effects EMPSTAT and LABFORCE for the 2004 ACS Sample.", class = c("haven_labelled", "vctrs_vctr", "integer")), W = c(4300.83677685951, 7721.46653212248, 11525.3777996555, 13877.6084883612, 15953.546319797)), row.names = c(NA, -5L), class = c("tbl_df", "tbl", "data.frame"))
尝试的代码:
rename(earnings_arts_22_65, t = AGE, W = income_mean) my_function <- function(t, W) {((((1/(1+r))^4 * sum((1/1+r)^(t-22) * W)))-D)(-sum((1/1+r)^(t-18) * W))} apply(earnings_arts_22_65, FUN = my_function(t, W), MARGIN = 2)
解决方法
1. 处理haven标签的非数值问题
报错根源是t为haven_labelled类型,带有标签属性,无法直接参与算术运算,先转成纯整数:
# 转换t为纯整数 earnings_arts_22_65$t <- as.integer(earnings_arts_22_65$t)
2. 重写符合需求的函数
原函数逻辑混乱,且存在未定义的r、D变量,按需求重写:
# 先定义折现率r,示例设为5% r <- 0.05 calculate_discounted_sum <- function(data) { # 筛选t在22到65之间的记录 filtered <- subset(data, t >= 22 & t <= 65) # 计算每条记录的折现值 discounted <- (1/(1+r))^(filtered$t - 22) * filtered$W # 返回求和结果 sum(discounted) }
3. 正确调用函数
不需要用apply,直接传入数据框调用函数即可:
# 计算结果 final_result <- calculate_discounted_sum(earnings_arts_22_65) print(final_result)
原代码的其他问题说明
- 函数中
r、D未定义,会导致额外报错 apply的FUN参数只需传函数名,不能直接传my_function(t,W)(这会直接执行函数而非传递函数对象)MARGIN=2是逐列处理,但需求需要同时用到t和W两列,逐列处理逻辑不成立
内容的提问来源于stack exchange,提问作者123
相关产品推荐
相关产品推荐

