R input names from a character vector to a function formula statement -


i aware there better solutions particular problem described below (e.g., cor , rcorr in hmisc, discussed here). illustration more general r issue can't figure out: passing multiple variable names character vector formula statement within function.

assume there dataset consisting of numeric variables.

vect.a <- rnorm(n = 20, mean = 0, sd = 1) vect.b <- rnorm(n = 20, mean = 0, sd = 1) vect.c <- rnorm(n = 20, mean = 0, sd = 1) vect.d <- rnorm(n = 20, mean = 0, sd = 1) dataset <- data.frame(vect.a, vect.b, vect.c, vect.d) names(dataset) <- c("var1", "var2", "var3", "var4") 

a correlation test has performed each possible pair of variables within data set, using formula statement of type ~ vara + varb within function cor.test:

for (i in 1:(length(names(dataset))-1)){     (j in (i+1):length(names(dataset))) {         cor.test(~ names(dataset)[i] + names(dataset)[j], data = "dataset")     } } 

which returns error: invalid 'envir' argument of type 'character'

i assume character string incompatible formula statement class compatible it? if entire approach wrong, please explain why , provide or point alternative solution. if approach somehow "ugly" or "non-r", please explain why.

you formula using as.formula string argument.

>> x <- c('x1','x2','x3') >> f <- as.formula(paste('~ ', x[1], ' + ', x[2])) >> f ~x1 + x2 >> class(f) [1] "formula" 

there issue here, data="dataset" should data=dataset, since dataset name.

> dataset <- data.frame(a=1:5, b=sample(1:5)) > cor.test(~ + b, data="dataset") error in eval(predvars, data, env) :    invalid 'envir' argument of type 'character' > cor.test(~ + b, data=dataset)  pearson's product-moment correlation ... 

Comments

Popular posts from this blog

get url and add instance to a model with prefilled foreign key :django admin -

android - Keyboard hides my half of edit-text and button below it even in scroll view -

css - Make div keyboard-scrollable in jQuery Mobile? -