chupvl
chupvl

Reputation: 1298

Column name for data frame

Hello I have a data frame in R that is a result of comparing one vector with big database (the db was read like this db <- read.table("database.txt", header = F, row.names = 1, sep = ",") ).

The problem is when I tried to name the columns using this piece of code colnames(some_matrix_with_example_below) <- c("name1","name2") R produced an error:

Error in `colnames<-`(`*tmp*`, value = c("name1", "name2")) : 
  length of 'dimnames' [2] not equal to array extent

Example of the matrix to rename

row.names   item
dbi1    1.0000000
dbi3    0.9431307
dbi4    0.9427034
dbi5    0.9259156
dbi6    0.9210256

As I correctly understand that the row.names is not treated like a column, is there easy way not to creating names and values object and binding them for further export?

Upvotes: 2

Views: 9421

Answers (1)

Gavin Simpson
Gavin Simpson

Reputation: 174938

Using

df <- read.table(text="row.names   item
dbi1    1.0000000
dbi3    0.9431307
dbi4    0.9427034
dbi5    0.9259156
dbi6    0.9210256", header=TRUE)

Note that df has two columns here.

> df
  row.names      item
1      dbi1 1.0000000
2      dbi3 0.9431307
3      dbi4 0.9427034
4      dbi5 0.9259156
5      dbi6 0.9210256

Now rename these names:

names(df) <- paste0("name", 1:2)

which gives

> df
  name1     name2
1  dbi1 1.0000000
2  dbi3 0.9431307
3  dbi4 0.9427034
4  dbi5 0.9259156
5  dbi6 0.9210256

Now when we write out this data frame we suppress writing of row names:

write.table(df, file = "my_data.txt", quote = FALSE, col.names = TRUE,
            row.names = FALSE, sep = ",")

we get the following file:

$ cat my_data.txt 
name1,name2
dbi1,1
dbi3,0.9431307
dbi4,0.9427034
dbi5,0.9259156
dbi6,0.9210256

I would separate the rounding step from the writing of the data to file. Also, you don;t need to convert to a matrix to use write.table() a data frame works fine.

df2 <- transform(df, name2 = round(name2, digits = 4))

gives

> df2
  name1  name2
1  dbi1 1.0000
2  dbi3 0.9431
3  dbi4 0.9427
4  dbi5 0.9259
5  dbi6 0.9210

then write it out as above. You can even combine the two steps if you wish:

write.table(transform(df, name2 = round(name2, digits = 4)),
            file = "my_data3.txt", quote = FALSE, col.names = TRUE,
            row.names = FALSE, sep = ",")

Upvotes: 2

Related Questions