For some reason specific to my R program, I want to assign column names and row names based on existing column and row in a dataframe in R. That is to say, the first line has to become the column names, and the first column has to become the row names.
I first thought it was easy, using :
colnames(myDataFrame) <- myDataFrame[1,]
rownames(MyDataFrame) <- myDataFrame[,1]
As it is also written in this topic.
But I have a lot of cases to handle in the first row and first column of my data frame : only text, text with numbers, text or numbers... That's why this sometimes does not work. See an example with only text in the first line :
I first load my data frame with no headers at all :
> tab <- read.table(file, header = FALSE, sep = "\t")
> tab
V1 V2 V3 V4 V5 V6 V7 V8 V9
1 TEST this is only text hoping it will work
2 I 4 0 0 0 0 0 0 1
3 really 7 6 6 3 10 6 10 10
4 hope 187 141 140 129 130 157 138 168
Here is my data frame without row and column names. I want "TEST this is only text hoping it will work" to become my column name. This doest not work :
> colnames(tab) <- tab[1,]
> tab
2 10 9 9 10 8 9 8 9
1 TEST this is only text hoping it will work
2 I 4 0 0 0 0 0 0 1
3 really 7 6 6 3 10 6 10 10
4 hope 187 141 140 129 130 157 138 168
Whereas this works :
> colnames(tab) <- as.character(unlist(tab[1,]))
> tab
TEST this is only text hoping it will work
1 TEST this is only text hoping it will work
2 I 4 0 0 0 0 0 0 1
3 really 7 6 6 3 10 6 10 10
4 hope 187 141 140 129 130 157 138 168
I thought the problem was because R sometimes considers the first column or row as factor. But as you can see :
> is.factor(tab[1,])
FALSE
It can fail even if it is not converted as factor by R.
I tried to tip "as.character(unlist()))" in my program, but in some other cases that I might encounter, it no longer works !... See an example with text and numbers in the first line :
> otherTab <- read.table(otherFile, header = FALSE, sep = "\t")
> otherTab
V1 V2 V3 V4 V5 V6 V7 V8 V9
1 TEST this45 is 486text 725 with ca257 some numbers
2 number45 4 0 0 0 0 0 0 1
3 254every 7 6 6 3 10 6 10 10
4 where 187 141 140 129 130 157 138 168
> colnames(otherTab) <- as.character(unlist(otherTab[1,]))
> otherTab
6 10 9 7 725 8 9 8 9
1 TEST this45 is 486text 725 with ca257 some numbers
2 number45 4 0 0 0 0 0 0 1
3 254every 7 6 6 3 10 6 10 10
4 where 187 141 140 129 130 157 138 168
So how to handle these different cases in a easy way (because this seems to be a so simple problem) ? Many thanks in advance.