[R] data.frame: How to get the classes of all components and how to remove their factor structure?

Marius Hofert m_hofert at web.de
Tue Jun 28 08:47:14 CEST 2011


Dear expeRts,

I have two questions concerning data frames:
(1) How can I apply the class function to each component in a data.frame? As you can see below, applying class to each column is not the right approach; applying it to each component seems bulky.
(2) After transforming the data frame a bit, the classes of certain components change to factor. How can I remove the factor structure?

Cheers,

Marius

x <- c(2004:2010, 2002:2011, 2000:2011)
df <- data.frame(x=x, group=c(rep("low",7), rep("middle",10), rep("high",12)), 
                 y=x+100*runif(length(x))) 

## Question (1): why do the following lines do not give the same "class"?
apply(df, 2, class)
class(df$x)
class(df$group)
class(df$y)

df. <- as.data.frame(xtabs(y ~ x + group, data=df))

class(df.$x)
class(df.$group)
class(df.$Freq)

## Question (2): how can I remove the factor structure from x?
df.$x <- as.numeric(as.character(df.$x)) # seems bulky; note that as.numeric(df.$x) is not correct
class(df.$x)


More information about the R-help mailing list