Francesca de Filippis
Francesca de Filippis

Reputation: 513

Order column in a table

I want to order the columns of a table. My data looks like this (I have 50 samples and 150 rows in the complete table):

> histo

 CD6 CD1 CD12
 Actinomyces 0.03196031 0.066683743 0.04563851
 Atopobium 0.01869159 0.003244536 0.00447774
 Streptococcus 0.23355000 0.452131300 0.15800000
 Veillonella 0.72330000 0.416600000 0.15000000
 Enterococcus 0.41223300 0.755200000 0.17400000

I tried this:

 > library(data.table)
 > df <- read.table(file="histo.txt", row.names=1, header=T, sep="")
 > setcolorder(df, c("CD1", "CD6", "CD12"))

But I got this error:

Error in setcolorder(df, c("CD1", "CD6", "CD12")) : x is not a data.table

Does anyone know how can I do?

Upvotes: 1

Views: 177

Answers (1)

jlhoward
jlhoward

Reputation: 59425

Several ways to do this.

df <- df[c("CD1", "CD6", "CD12")]    # no need for data tables

dt <- data.table(df)                 # as per @BenBolker
setcolorder(dt,c("CD1", "CD6", "CD12"))

The difference is that with data tables you do not copy the result, you just move the rows around. This is faster with really large tables, but not significant in your case.

Upvotes: 3

Related Questions