是否可以通过以方括号格式指示变量名来使用“摘要”功能?

时间:2019-05-09 16:32:32

标签: r function

我在编程一个函数以计算加权平均值和标准差时遇到问题(错误消息:“ summarise_impl(.data,点)中的错误:评估错误:二进制运算符的非数字参数”)。

对于可复制的数据,

set.seed(1)
sample<-as.data.frame(cbind(treat, weight))
treat<-c(rep(0, 10), rep(1, 10))
weight<-runif(20)
for (i in 1:nrow(sample)){
  sample$Y1[i]<-sample$treat[i] + rnorm(1, mean = 0, sd = 1)
  sample$Y2[i]<- -sample$treat[i] + rnorm(1, mean = 0, sd = 1)
}
sample[3, "Y1"]<-NA
sample[5, "weight"]<-NA
sample[1, "weight"]<1000

而且,我正在使用的功能的代码如下。

func<-function(data.name, varlist, cond.var, relation, comp.value, gen.var){

   varlist.de<-unlist(strsplit(varlist, "[+]"))

 ### This is where I ecnountered the problem
  for (i in 1:nrow(data.name)){
   for (j in 1:(length(varlist.de)-2)){
      df_weighted<-
           data.name %>% 
                  summarise(weighted_mean = wt.mean(varlist.de[j+2], varlist.de[j+1]), 
                            weighted_sd = wt.sd(varlist.de[j+2], varlist.de[j+1]))
       }
    }

 return(data.name)

}

## I ran this code, then the error occured. 
func(data.name=sample, 
    varlist="treat+weight+Y1+Y2", 
    cond.var="weight", 
    relation = "!=", 
    comp.value = "NA", 
    My_New_Index1)

具体来说,“ df_weighted <-数据名%>%group_by(TT)%>%摘要(weighted_mean = wt.mean(varlist.de [j + 2],varlist.de [j + 1]),weighted_sd = wt.sd(varlist.de [j + 2],varlist.de [j + 1]))”似乎会生成错误消息,即“ summarise_impl(.data,点)中的错误:评估错误:非数字参数二进制运算符”。

任何解决错误的建议将不胜感激。谢谢。

0 个答案:

没有答案