简体   繁体   English

SAS中R中的等效宏代码

[英]Macro code equivalent in R from SAS

This may be simple, so apologies in advance - I'm a very novice R coder. 这可能很简单,所以提前道歉-我是R语言的新手。 I'm looking to code the below SAS macro as a function in R (this is from memory, as I don't have SAS outside work): 我想将下面的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)

I've coded this up so far, but I'm having trouble triggering emp_stat1 and emp_stat2 from the one x=emp_stat input. 到目前为止,我已经对此进行了编码,但是在从一个x = emp_stat输入触发emp_stat1和emp_stat2时遇到了麻烦。 Is this possible? 这可能吗?

coalesce.func <- function(x) {
survey_results$x <- coalesce(survey_results$x1,survey_results$x2)
}

Thanks! 谢谢!

# 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

If you wanted to have a proc sql equivalent in R you could use the sqldf package. 如果要在R中具有等效的proc sql ,可以使用sqldf软件包。 This function should be equivalent to the function above. 此功能应与上面的功能等效。

library(sqldf)
library(glue)

coalesce.fun <- function(x){
  sqldf(glue('
  select coalesce({x}1, {x}2) as {x}
  from survey_results
  '))
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM