List of input variables without manually adding a comma between them

Essentially, I would like to achieve this:

vars <- c(x1, x20, x37, etc)
summary(data[vars])

However, my list of variables is quite long and does not contain commas between them.

Edit: Datahas 500 variables, and varsis the list that I want to select. Variable names do not match the pattern. The list is in the form x1 x20 x37 etc, i.e. Separated by spaces. This list comes from the SAS syntax file and is not part of the R workspace.

I looked at a function that combines variables with a separator, for example cat(). But this requires an object from the very beginning. Another way is to use find / replace in the editor (space to a comma), but I find this a dirty hack.

Obviously, I'm missing something when defining a list of variables; There should be a simple solution.

+3
source share
3 answers

Use this:

data <- data.frame(x1 = rnorm(10), x2 = rnorm(10))
vars <- "x1 x2"
data[unlist(strsplit(vars, ' '))]
+7
source

Looks like they are already variable names in your workspace?

x <- ls()[grep('^x\\d', ls())]

This can lead you there if you have nothing that starts with x and the number you want to include.

If these are text strings that you insert or something, then maybe

x <- scan()

(All in all, your question was rather vague)

+2
source

, ( , , ): . :

df <- read.table("foo.txt", sep=" ")

names(df); ,

df <- read.table("foo.txt", header=TRUE, sep=" ") 
+1
source

All Articles