Automation of output of several variables from an object

Here is my situation. I have an object that I created with read.spss.

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

Now in this object athere are asked questions that I would like to pull out, following the sequence of question numbers:

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

Is there a way to automate it so that it pulls out all the questions, starting from q3_the original object to the new q3 data.frame?

I tried using the function to pasteno avail.

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

This simply returns a data.framewith the inserted sequence.

Ideally, I would like something that draws in everything from a question starting with qX_, since some values ​​are missing or outdated.

+3
source share
3

grep, match %in%. , 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> 
+5
q3 <- a[,grep("q3_",colnames(a))]
+2

I would just do something like:

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

You can use attach(a)it if you want (and if there is no element in ` a` named ' a'), but not necessary.

0
source

Source: https://habr.com/ru/post/1717593/


All Articles