Extract rows name in R
3
0
Entering edit mode
7 weeks ago
ryme ▴ 10

I have a data frame with several rows. I want to select the row's names of this data frame and put them into a new variable. The input example dataframe is as follows:

I want to extract the row's names of the first column (X) (ENSG000...). I tried to use the rownames() function:

genes_name <- as.character(rownames(dataframe))


Results:

It didn't extract the row names of X but the numbers.

Please could anyone help me?

rows R • 255 views
3
Entering edit mode
7 weeks ago
Papyrus ★ 1.2k

That data.frame does not seem to have rownames. Your "rownames" are in fact the first column, named "X", accesible through dataframe$X, or dataframe[,1] or dataframe[,"X"] ADD COMMENT 0 Entering edit mode Thank you for your response. I tried : genes_name <- as.character(rownames(dataframe$X))

genes_name <- as.character(rownames(dataframe[,1]))


and genes_name <- as.character(rownames(dataframe[,'X'])) but still not working.

Results: NULL (empty)

1
Entering edit mode

Yes, because the rownames() function tries to extract rownames, which you do not have. Instead, simply do genes_name <- as.character(dataframe\$X).

0
Entering edit mode
7 weeks ago

I second the answer provided by @Papyrus above. Also, I have frequently run into this issue when reading external data in to R. If you want the first column of the table to be the row names of the data frame in R, you can set the row.names parameter to 1 when reading in the data. Hope you find this helpful!

0
Entering edit mode
7 weeks ago

You asked for rownames, R gave you numbers. Those are your rownames, not the contents of X. Usually, when you import into R, your rowname column should not have a column name too.

As mentioned already, you can specify row.names when importing the file, or you can always assign new rownames within R. Or, if you want the gene names, just get the contents of the column you want, row name or not.