如何将动态矢量作为参数传递给R中的函数?

时间:2019-03-09 13:36:24

标签: r function arguments

chol1 <- structure(list(sex = structure(c(2L, 2L, 2L, 1L, 2L),.Label = c("F","M"), class = "factor"), age = c(60L, 26L, 33L, 27L, 36L), 
chol =c(137L, 154L, 198L, 154L, 212L), tg = c(50L, 202L, 108L, 47L, 79L), ht =c(68.25,82.75, 64.25, 63.25, 67.5), wt = c(111.75, 184.75, 147, 129,176.25), sbp = c(110L, 88L, 120L, 110L, 130L), dbp = c(70L, 64L,80L, 76L, 100L), vldl = c(10L, 34L, 22L, 9L, 16L), hdl = c(53L,31L, 34L, 57L, 37L), ldl = c(74L, 92L, 132L, 88L, 159L), bmi =c(2.399066135,2.698040361, 3.560992596, 3.224546548, 3.868312757)), class = c("data.table","data.frame"), row.names = c(NA, -5L)) 

我正在尝试传递我的整个数据框,但要求类似于功能(数据框,col1,c(“ wt”,“ tg” ...))

 myCortest_final=function(df,type="pearson"){
 df1=df[,sapply(df, is.numeric), with=FALSE] # only keep numeric variables in data frame
df2=df[,sapply(df, is.integer), with=FALSE] # only keep integer variables in data frame
          df = merge.data.frame(df1, df2) #binding both the columns in one dataframe df
          vars=names(df)
          nvars=length(vars)
          nvals=(nvars*nvars-nvars)/2 # number of pairwise correlations between the variables
          vars1=vars2=cors=pvals=n=vector("numeric",nvals) # make empty vectors to store results
          row=1 # row of output table
          for (v1 in (1:(nvars-1))) {
            for (v2 in ((v1+1):nvars)) {
              var1=vars[[v1]]; var2=vars[[v2]]
              vars1[[row]]=var1; vars2[[row]]=var2
              out=cor.test(df[,var1],df[,var2],use="pairwise.complete.obs",method=type)
              cors[[row]]=out$estimate
              pvals[[row]]=out$p.value
              n[[row]]=out$parameter+2 # df + 2
              row=row+1
             }
          }
          data.frame(cbind(var1=vars1,var2=vars2,r=cors,p=pvals,n),row.names=NULL)
        }

        myCortest_final(chol)

I want something like myCortest_final=function(df,columnName1,columnVector,type="pearson")

我想要一个变量与其他变量的关系。(作为函数的args动态键入)

0 个答案:

没有答案