Mohsin Waqas
Mohsin Waqas

Reputation: 47

Convert a table without any col and row name created from a matrix to data frame

I wrote a code for my matrix that I want to create

tstp<-matrix(1:200, ncol = 4, byrow = TRUE)

And then I wrote this code to get my required format

write.table(tstp, row.names = FALSE, col.names = FALSE, quote = FALSE, sep = "\t")

I am here presenting the first four rows. The out is like that

1   2   3   4
5   6   7   8
9   10  11  12
13  14  15  16

It is my required output if its class will be data frame. So I wrote a code to convert it into data frame that is given as

> timestp<-data.frame(tstp)

And the output from the code has created the column names and row number that are not required as shown below.

> timestp
  X1 X2 X3 X4
1  1  2  3  4
2  5  6  7  8
3  9 10 11 12
4 13 14 15 16

its produced the class that I need

> class(timestp)
[1] "data.frame"

But I want output like given below with class of data.frme

1   2   3   4
5   6   7   8
9   10  11  12
13  14  15  16

Upvotes: 2

Views: 1416

Answers (2)

Ronak Shah
Ronak Shah

Reputation: 389135

We can use as.data.frame with optional parameter set to TRUE

timestp <- as.data.frame(tstp, optional = TRUE)

colnames(df)
#NULL

Upvotes: 2

M--
M--

Reputation: 29109

You can do this:

rownames(timestp) <- NULL
colnames(timestp) <- NULL

or if you only want to exclude row names, then use this:

timestp<-data.frame(tstp, row.names = NULL)

However, when you print it will show the numbers (as indices, not names). Refer to "Removing display of R row names from data frame".

You have successfully removed the rownames. The print.data.frame method just shows the row numbers if no rownames are present.

If you want to exclude the row numbers while printing then this will help you:

print(timestp, row.names = FALSE)

This will be the output:

> print(head(timestp), row.names = FALSE)

 # 1  2  3  4
 # 5  6  7  8
 # 9 10 11 12
 # 13 14 15 16
 # 17 18 19 20
 # 21 22 23 24

Upvotes: 2

Related Questions