Roman Cheplyaka
Roman Cheplyaka

Reputation: 38758

Print one column of data frame with row names

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?

Upvotes: 36

Views: 107654

Answers (4)

urvi jain
urvi jain

Reputation: 59

Simply, use select with column slicing:

data %>%
    select(1:2) %>%
    head

Upvotes: 0

ikwee
ikwee

Reputation: 127

In contrast to data.frames, getting a column from matrices in R seem to retain their (row)names. One of the (many!) weird inconsistencies I find in R... To get a named vector one of these seems to work:

as.matrix(data['c'])[,1]

or

array(data['c'], dimnames=list(rownames(data)))

Upvotes: 0

amc
amc

Reputation: 843

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

  c
x 3
y 4
z 5

Upvotes: 6

user1981275
user1981275

Reputation: 13382

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

data[,"c", drop=FALSE]

gives you a data.frame

  c
x 3
y 4
z 5

Upvotes: 45

Related Questions