lxcfuji
lxcfuji

Reputation: 339

Error check: how to extract many columns into data frame and make them into one column in R

I have three columns that want to put into a data frame, and also make it into one column. I already signed each column with a unique ID. And the result I want is two columns, one is column ID, and one is these three column values. These are my original data:

so I want the result like:

1 value
2 value
3 value
1 value
2 value
3 value

So what I did is:

for (i in 1:nrow(cancer)) 
+   for (j in 1:ncol(cancer)){  
+        
+     dtypeID=datatype$dtypeID[datatype$dtype %in% names(cancer)[j]]
+     if (nrow(cancerdata)==0){
+       cancerdata = data.frame(dataID=1,
+                         dtypeID=dtypeID,
+                         value=cancer[i,j]) 
+     } else {
+       
+       lastdataID = max(cancerdata$dataID)
+       dataID=lastdataID+1
+       newline = data.frame(dataID=dataID, 
+                            dtypeID=dtypeID,
+                            value=cancer[i,j])
+       
+       cancerdata=rbind(cancerdata, newline)  
+     } 
+   }

But it keep getting me this error: Error in data.frame(dataID = 1, dtypeID = dtypeID, value = cancer[i, j]) : arguments imply differing number of rows: 1, 0

Upvotes: 0

Views: 38

Answers (1)

David Robinson
David Robinson

Reputation: 78590

It looks like what you are trying to do is melt the data. Install the reshape2 package and try:

library(reshape2)
cancerdata = melt(cancer, id=c("Gene.symbol", "Pathway.title"))

(You can install reshape2 with install.packages("reshape2")).

Upvotes: 1

Related Questions