symbolrush
symbolrush

Reputation: 7457

Replace the values in a named numeric by its attribute value.label

I have a sample df that looks like:

sample <- structure(list(
  var = structure(c(1, 2, 2, 3, 2), 
                  value.labels = c(
                    no = 3, `yes, opinion` = 2, `yes, decision` = 1))), 
  row.names = c(NA, -5L), 
  class = "data.frame")

Obviously sample$var is a categorical variable and the levels are stored in the attributes of the vector var:

attributes(sample$var)
# $value.labels
#       no  yes, opinion yes, decision 
#        3             2             1

..but I can't make sense of those attributes..

For example table(sample$var) doesn't show them:

table(sample$var)

# 1 2 3 
# 1 3 1 

And also any attempts to bring them to 'life' by as.factor (and - desperately searching - as.character) didn't work out.


How can I replace those values with their corresponding labels? Expected output can be a vector of class factor or string..


And a bit 'around' the question: What exactly is the idea behind that kind of named vectors (in addition to the factor class..)?

Upvotes: 2

Views: 826

Answers (2)

Ronak Shah
Ronak Shah

Reputation: 388982

You may add a new column with labels. Then you can use table or other functions on them as usual.

tmp <- attributes(sample$var)$value.labels
sample$label <- names(tmp)[match(sample$var, tmp)]
sample

#  var         label
#1   1 yes, decision
#2   2  yes, opinion
#3   2  yes, opinion
#4   3            no
#5   2  yes, opinion

table(sample$label)

#           no yes, decision  yes, opinion 
#            1             1             3 

Upvotes: 2

GKi
GKi

Reputation: 39667

You can try to bring them to life:

. <- attr(sample$var, "value.labels")
table(factor(sample$var, ., names(.)))
#           no  yes, opinion yes, decision 
#            1             3             1 

or overwrite:

. <- attr(sample$var, "value.labels")
sample$var <- factor(sample$var, ., names(.))

Upvotes: 2

Related Questions