如何在R的aw_weight()函数中传入变量作为areaWeight参数?
解决R语言aw_weight()循环中动态设置areaWeight列名的问题
我明白你遇到的问题了——在循环里想用动态生成的名字作为新列名,但aw_weight()却把paste0(...)这个表达式本身当成了列名,而不是计算后的areaWeight1这类名字。
问题出在函数的参数处理逻辑上:aw_weight的areaWeight参数如果直接传入表达式(比如paste0(...)),它会把表达式文本当作字符串使用,而不会先求值得到最终的列名字符串。另外你的代码里还有个小疏漏:paste0(areaWeight, n)中的areaWeight没有定义成字符串常量,应该写成paste0("areaWeight", n)才对。
下面是两种可行的解决方法:
方法1:先预存动态列名(最直观)
先把要生成的列名计算出来存在变量里,再把变量传给areaWeight参数:
library(areal) # 假设你的intersect对象已经准备好 for (n in c("1","2","3")) { # 先计算出目标列名字符串 new_weight_col <- paste0("areaWeight", n) # 调用函数,传入预存的列名 intersect <- aw_weight(intersect, areaVar = "area", totalVar = "totalArea", areaWeight = new_weight_col) }
方法2:使用非标准求值强制表达式求值
如果习惯用tidyverse风格的非标准求值,可以用rlang包的工具强制让表达式先求值:
library(areal) library(rlang) for (n in c("1","2","3")) { # 用!!sym()强制解析计算后的字符串 intersect <- aw_weight(intersect, areaVar = "area", totalVar = "totalArea", areaWeight = !!sym(paste0("areaWeight", n))) }
两种方法都能帮你生成areaWeight1、areaWeight2、areaWeight3这样的动态列名,建议用第一种,更直观易懂,也不需要额外加载rlang包。
内容的提问来源于stack exchange,提问作者Squirrel K
相关产品推荐
相关产品推荐

