NWaters
NWaters

Reputation: 1213

Defining the levels of dataframe columns in R

I am trying to redefine the levels that are assigned when I am using cbind to create a dataframe from select columns of other dataframes. The dataframes contain integers, and the rownames are strings:

outTable<-data.frame(cbind(contRes$wt, bRes$log2FoldChange, cRes$log2FoldChange, dRes$log2FoldChange, aRes$log2FoldChange), row.names=row.names(aRes))

Using the following, I get the levels of the columns:

levels(as.factor(colnames(outTable)))
[1] "F" "N" "RH" "RK" "W"  

I would like to change that order by passing something like:

levels(as.factor(colnames(outTable)))<-c("W", "RK", "RH", "F", "N")

but I get the error:

could not find function "as.factor<-"

The end purpose is to set the X axis order of a boxplot in ggplot2. Am I approaching this the right way? if so, what am I missing, and if not how would be the best way to?

Upvotes: 0

Views: 2589

Answers (2)

C_Z_
C_Z_

Reputation: 7816

You can specify levels as an argument in the as.factor function

factor(colnames(outTable), levels = c("W", "RK", "RH", "F", "N"), ordered=T)

Upvotes: 0

MrFlick
MrFlick

Reputation: 206546

Use

factor(colnames(outTable), levels=c("W", "RK", "RH", "F", "N"))

If you use levels()<- you will simply rename/replace level names; you don't re-order them. This is certainly not he behavior you want. The best way to re-order them all is to just use factor()

Upvotes: 1

Related Questions