Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to subset a melt object

My issue

I have melt object from reshape2 library.

I would like to subset variables with value==1.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

However, when I select value from subset melt object, I get the id instead of variable.

How to get a vector where I end up with an output vector==[1] "varD" "varA"?

Reproducible example

### Import library
library(reshape2)

### Initiating dataframe
dftmp <- data.frame(id=1:3,
                    varA=1:3,
                    varB=4:6,
                    varC=7:9)

### Melt dataframe
melttmp <- melt(dftmp, id.vars="id")

### Selecting variable with value==1
varValue1 <- subset(melttmp, value==1)$variable

### Vector of varD and variable with value==1
output <- c("varD", varValue1)
output
[1] "varD" "1" 

>Solution :

Because that column is a factor – it is an integer with a label, so it gets converted to a number, in your case 1. We need to convert to character:

varValue1 <- as.character(subset(melttmp, value==1)$variable)

output <- c("varD", varValue1)
output
# [1] "varD" "varA"
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading