r - 来自 SAS 的 R 中的等效宏代码
问题描述
这可能很简单,所以提前道歉 - 我是一个非常新手的 R 编码器。我正在寻找将以下 SAS 宏编码为 R 中的函数(这是来自内存,因为我在工作之外没有 SAS):
%macro coalesce(x=);
proc sql;
create table test as select *
, coalescec(&x.1,&x.2) as &x
from survey_results;
quit;
%mend;
%coalesce(x=emp_stat)
到目前为止,我已经对此进行了编码,但是我无法从一个 x=emp_stat 输入触发 emp_stat1 和 emp_stat2。这可能吗?
coalesce.func <- function(x) {
survey_results$x <- coalesce(survey_results$x1,survey_results$x2)
}
谢谢!
解决方案
# create data
set.seed(21)
survey_results <- data.frame(a1 = sample(c(NA, 'q'), 10, T)
, a2 = sample(c(NA, 'w'), 10, T)
, stringsAsFactors = F)
survey_results
# # a1 a2
# 1 q w
# 2 <NA> w
# 3 q <NA>
# 4 <NA> w
# 5 q <NA>
# 6 q <NA>
# 7 <NA> w
# 8 <NA> <NA>
# 9 q <NA>
# 10 q w
library(dplyr) #loaded to use 'coalesce' function included in package
coalesce.fun <- function(x, df = survey_results){
# call coalesce on the input x pasted to . and the vector 1 to 2
# create data frame with it
# assign to 'out'
out <- data.frame(do.call(coalesce, df[paste0(x, 1:2)]))
# set column names to input
colnames(out) <- x
# return 'out'
out
}
test <- coalesce.fun('a')
# # a
# 1 q
# 2 w
# 3 q
# 4 w
# 5 q
# 6 q
# 7 w
# 8 <NA>
# 9 q
# 10 q
如果你想proc sql
在 R 中有一个等价物,你可以使用这个sqldf
包。这个函数应该等同于上面的函数。
library(sqldf)
library(glue)
coalesce.fun <- function(x){
sqldf(glue('
select coalesce({x}1, {x}2) as {x}
from survey_results
'))
}
推荐阅读
- javascript - 如何更新嵌套的 MongoDB 对象
- html - 在使用“form-group row”时使用引导程序添加输入,但发送到下一行
- c# - C# 属性值对某些是通过引用,对另一些是通过值
- c# - Unity 广告根本不显示并出现错误“实施 IUnityAdsListener 并调用 Advertisement.AddListener()”
- sas - 如何在 SAS 中将条件作为宏参数传递
- logstash - 如何将 linux 托管日志作为 filebeat.yml 中的输入路径?
- javascript - 如何计算多个值之间的范围?
- python - Python - 有效地将相同的值分配给列表切片
- algorithm - 清理数据集中的短段
- javascript - 如何使用 Bootstrap Carousel 更改幻灯片?