Nancy
Nancy

Reputation: 4089

Mapping attributes to values in vector

I'm working with a dataframe where each column has different attributes. Is it possible to map specified attributes to the vector? For context, you might expect to see this situation where you have raw data and labeled data in the form of a vector and a label attribute.

Here is an example with the desired outcome:

foo = c(2,1,3,3,2,1)
attr(foo, "mylevels") = c(1,2,3)
attr(foo, "mylabels") = c("Red", "Blue", "Green")

## foo
## [1] 1 2 3 3 2 1
## attr(,"mylevels")
## [1] 1 2 3
## attr(,"mylabels")
## [1] "Red"   "Blue"  "Green"

## attributes(foo)
## $mylevels
## [1] 1 2 3

## $mylabels
## [1] "Red"   "Blue"  "Green"

The goal is something like:

foo[attr(foo, "mylabels")] #(which doesn't work)
"Blue" "Red" "Green" "Green" "Blue" "Red"

Upvotes: 0

Views: 68

Answers (1)

akrun
akrun

Reputation: 887118

We can either convert the 'foo' to factor and specify the levels

as.character(factor(foo, labels=c("Red", "Blue", "Green")))

Or use the 'foo' as numeric index for the attr

attr(foo, "mylabels")[foo]

Upvotes: 1

Related Questions