0

I have a dataset that has one column for IDs and then 100 columns listing the scores for each of 100 questions, like so:

ID     Q1     Q2     ...     Q100
S1      1      1     ...        1

I've written my code as follows:

library(reshape2)
new_df <- melt(df, id.vars = "ID", measure.var = c("Q1", "Q100))

However, this obviously doesn't work--it only melts the Q1 and Q100 column. Is there a way to melt Q1 to Q100 either using a string, or using the column locations (i.e., [,2:101]?)

Thanks!

  • Please indicate from where `melt` is coming, not only in the title. –  Feb 27 '15 at 02:54
  • What happens if you just use `melt(df, id.vars="ID")`? – coffeinjunky Feb 27 '15 at 02:54
  • @coffeinjunky: The dataset has hundreds of other variables as well. I just want to select (subset?) these. –  Feb 27 '15 at 03:12
  • But you said that the dataset has 100 columns (i.e. variables). –  Feb 27 '15 at 03:17
  • @Pascal: Sorry, I was thinking that those were the columns I wanted to select instead. The dataset itself has approximately 1000 columns of information. I just didn't want to have to enumerate each variable in the measure.var = , if I didn't have to. –  Feb 27 '15 at 03:19
  • According to `?melt`, `measure.vars: vector of measured variables. Can be integer (variable position) or string (variable name)If blank, will use all non id.vars`. So you can use `measure.var = 2:101` I guess. –  Feb 27 '15 at 03:27
  • It is simply what you mentioned in your post. –  Feb 27 '15 at 03:33
  • 1
    You could also use something like `paste("Q", 1:200)` if you were unsure of the indices... – Richard Border Feb 27 '15 at 04:06

1 Answers1

0

Since you said that you have hundreds of other variables, I created a sample data frame with variables ID,Q1 to Q5 and some variables with random names.

df <- data.frame(ID=c(1:20),Q1=sample(1:20,replace=T),
                    Q2=sample(1:20,replace=T),
                    Q3=sample(1:20,replace=T),
                    Q4=sample(1:20,replace=T),
                    sekf=sample(1:20,replace=T),
                    Q5=sample(1:20,replace=T),
                    rew=sample(1:20,replace=T)
                    )

#Counting variable names with "Q"
a <- paste("Q",1:(ncol(df)),sep="") %in% names(df)
 a2<- sum(a==T)


new_df <- melt(df, id.vars = "ID", measure.var = paste("Q",1:a2,sep=""))

Hope this is helpful.

jbest
  • 640
  • 1
  • 10
  • 28