0

我有一个数据集,其中有一列用于 ID,然后 100 列列出了 100 个问题中每个问题的分数,如下所示:

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

我编写了如下代码:

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

但是,这显然不起作用——它只会熔化 Q1 和 Q100 色谱柱。有没有办法使用字符串或使用列位置(即 [,2:101] )将 Q1 融化到 Q100?

谢谢!

4

1 回答 1

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.

于 2015-02-27T07:26:38.253 回答