rreshape

How to subset a melt object


My issue

I have melt object from reshape2 library.

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

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"