Creating a vector of string or numeric from a factor vector using the factors levels: a transformation of sorts

tuxedo_warefolf

I’ve used this handy bit of code quite a bit. It comes in handy when I want to use something that has been coerced to type=factor. I run into this quite a bit after a table() call when I want to do something more interesting with the result (e.g., convert to a data.frame and sort or select rows by the bin name).

vec <- round(12 + rnorm(100, 5, 7), 0)
t1 <- table(vec)
df1 <- data.frame(t1)
df1
class(df1$vec)
df1$vec <- as.numeric(levels(df1$vec))[df1$vec]
df1
class(df1$vec)

Advertisements

2 thoughts on “Creating a vector of string or numeric from a factor vector using the factors levels: a transformation of sorts

  1. This is actually useful, You’re a really skillful article publisher. We have registered with all your give food to additionally expect picking out the wonderful write-ups. In addition, I have shared your individual internet-site with the internet sites.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s