tags:

views:

82

answers:

4

Here's my situation. I have an object that I've created using read.spss.

> a <- read.spss(...)
> attach(a)

Now in this object (a) is a set questions that I would like to pull out that follows a sequence of question numbers.

> q3 <- data.frame(q3_1, q3_2, q3_4, ... q3_27)

Is there a way to automate it such that it pulls out all questions starting with "q3_" from the original object into the new q3 data.frame?

I've tried using the paste function to no avail.

> q3 <- data.frame(paste("q3_",1:27,sep=""))

That just returns a data.frame with the pasted sequence.

Ideally, I would like something that pulls in everything from a question beginning with a "qX_", as some values are missing or outdated.

Thanks in advance!

+5  A: 

Among the possibilities are grep, match and %in%. Here is a solution using grep:

R> foo <- data.frame(q1_1=1:4, q1_2=11:14, q2_1=21:24, q2_2=31:34, q3_1=41:44, q3_2=51:54)
R> colnames(foo)
[1] "q1_1" "q1_2" "q2_1" "q2_2" "q3_1" "q3_2"
R> grep("q3_", colnames(foo))
[1] 5 6
R> q3 <- foo[, grep("q3_", colnames(foo))]
R> q3
  q3_1 q3_2
1   41   51
2   42   52
3   43   53
4   44   54
R>
Dirk Eddelbuettel
+2  A: 
q3 <- a[,grep("q3_",colnames(a))]
Rob Hyndman
+1  A: 

I asked a similar question a week ago. Shane provided the grep solution - which is really usefull. Kpierce8 provide a different solution - that might be of use

Andreas
A: 

I'd just do something like:

q3 <- data.frame(a[paste('q3_',1:27,sep='')])

You can still use attach(a) if you like (and if there's no element in 'a' named 'a'), but there is no need.

Peter McMahan