2

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" 
2
  • 2
    Is there a good reason you're using reshape2? It's GitHub repo states, reshape2 is superseded: only changes necessary to keep it on CRAN will be made. We recommend using tidyr instead.
    – SamR
    Commented Jun 25 at 13:33
  • It was the most straight-forward method but I will look into tidyr pivot functions. Thanks for the recommendation Commented Jun 25 at 13:37

1 Answer 1

2

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"
0

Not the answer you're looking for? Browse other questions tagged or ask your own question.