Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Print one column of data frame with row names

Tags:

dataframe

r

Consider a data frame with custom row names:

> data <- data.frame(a=1:3,b=2:4,c=3:5,row.names=c("x","y","z")) > data   a b c x 1 2 3 y 2 3 4 z 3 4 5 

If I select more than one column, R prints them along with the row names:

> data[,c("a","c")]   a c x 1 3 y 2 4 z 3 5 

But if I select only one column, R prints it as a simple vector, without the row names:

> data[,"c"] [1] 3 4 5 

My question is, how do I tell R to print one column in the same way it prints multiple columns, that is, with the row names?

like image 389
Roman Cheplyaka Avatar asked Apr 08 '13 10:04

Roman Cheplyaka


People also ask

How do I print Dataframe column names?

To access the names of a Pandas dataframe, we can the method columns(). For example, if our dataframe is called df we just type print(df. columns) to get all the columns of the Pandas dataframe.

How do I get one column from a Dataframe?

This is the most basic way to select a single column from a dataframe, just put the string name of the column in brackets. Returns a pandas series. Passing a list in the brackets lets you select multiple columns at the same time.


2 Answers

You can use the drop argument (see also ?'['):

data[,"c", drop=FALSE] 

gives you a data.frame

  c x 3 y 4 z 5 
like image 61
user1981275 Avatar answered Sep 28 '22 09:09

user1981275


An even easier way is data['c'], which will result in the same output:

  c x 3 y 4 z 5 
like image 37
amc Avatar answered Sep 28 '22 09:09

amc