Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set the row index name in R? (Like DF.index.name in Pandas)

How can I set the row index name in a R data.frame object?

I tried looking on stackoverflow for the answer but I couldn't figure out how to even search for it? https://stackoverflow.com/search?q=set+row+index+name+dataframe+R

This one kind of explains it but they are converting it to a matrix? How do I name the "row names" column in r

> dimnames(DF_c) = c("sample","cluster")
Error in `dimnames<-.data.frame`(`*tmp*`, value = c("sample", "cluster" : 
  invalid 'dimnames' given for data frame

In Python Pandas, I would simply do DF_c.index.name = "samples" but I don't know how to do it in R. I noticed that when I saved it write.table(DF_c, "output.tsv", sep="\t") It puts my column label as the row name but I can't do something like colnames(DF_c) = c( "samples","cluster") since there is only 1 column?

# Clusters
DF_c = data.frame(last_iter$c)
rownames(DF_c) = row_labels
colnames(DF_c) = c( "cluster")

Bonus: How to not include the " when it's writing table to output?

enter image description here

like image 472
O.rka Avatar asked Oct 30 '22 21:10

O.rka


1 Answers

You are setting the row names and column names correctly, you just missed a piece from your 'write.table' command to remove the quotes:

write.table(DF_c, "output.tsv", sep="\t", quote = FALSE)

The reason that your column name goes over the row name in your output table seems to be a weirdness of R, you can get around it by creating a column for your row names with a column label, then writing the table out:

DF_c = data.frame(last_iter$c)
colnames(DF_c) = c( "cluster")
DF_c$rownames = row_labels

write.table(DF_c, "output.tsv", sep="\t", quote = FALSE)
like image 56
Kirsten Gotting Avatar answered Nov 09 '22 12:11

Kirsten Gotting