如何编写R自定义函数为任意列数数据框生成指定逻辑规则的两个新列
解决代码
首先需要提前加载dplyr包使用lag函数,和你原有代码逻辑保持一致:
library(dplyr)
修改后的完整函数:
my.spec.df <- function(data, variables, new.var.name){ new.df <- data # 预生成第二个新列名,解决动态命名问题 conj_name <- paste0("Conj.Var.", new.var.name) # 生成第一个新列,适配任意数量输入变量 lag_equal_mat <- sapply(new.df[variables], function(x) x == lag(x, 1)) new.df[[new.var.name]] <- as.integer(rowSums(lag_equal_mat, na.rm = TRUE) == length(variables)) # 生成第二个新列,适配任意数量输入变量 all_one_mat <- sapply(new.df[variables], function(x) x == 1) all_one_cond <- rowSums(all_one_mat) == length(variables) new.df[[conj_name]] <- as.integer(all_one_cond & new.df[[new.var.name]] == 1) return(new.df) }
测试验证
# 构造测试数据 V1 <- c(1, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 0) V2 <- c(0, 1, 1, 1, 0, 1, 0, 0, 0, 1, 1, 1, 0, 1, 0) Data <- data.frame(V1, V2) # 调用函数 spec.df <- my.spec.df(Data, variables=c("V1", "V2"), new.var.name="NV1") # 输出结果和你预期完全一致 print(spec.df)
难点对应解决方法
- 可变变量逻辑适配:通过
sapply批量遍历所有传入的变量计算逻辑值,用rowSums判断所有变量是否同时满足条件,支持1到任意数量的变量输入。 - 动态列名生成:用
paste0拼接前缀和第一个新列的名称,通过[[ ]]操作符使用字符串作为列名赋值,解决$操作符无法使用动态变量名的问题。 - 第二列逻辑适配:和第一列逻辑思路一致,批量判断所有指定变量是否等于1,再结合第一个新列的条件做与运算即可。
内容的提问来源于stack exchange,提问作者CNiessen
相关产品推荐
相关产品推荐

