35

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?

1
  • 2
    @user1981275's answer works because when you're subsetting using [, "c"], R tries to simplify object class. Telling him not to "drop" it, preserves your data.frame class. Apr 8, 2013 at 11:37

4 Answers 4

45

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

data[,"c", drop=FALSE]

gives you a data.frame

  c
x 3
y 4
z 5
4
  • This is similar to subset(data,select="c") and this generates a one-column dataframe. Do you konw how to get a named character vector instead ? (cc @RomanCheplyaka) Dec 4, 2013 at 19:30
  • I could only think of apply(data[,"c", drop=FALSE], 1, c) but maybe there is be a simpler solution. Dec 5, 2013 at 11:46
  • Or if you really want a named character vector apply(data[,"c", drop=FALSE], 1, as.character, c) Dec 5, 2013 at 11:48
  • I know is long ago, but on the posts of @user1981275: for me apply(data[,"c", drop=FALSE], 1, as.numeric) works better, first I get problems with the c at the end and for this data example as.numeric seems to be better
    – N.Varela
    Feb 8, 2016 at 8:32
6

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

  c
x 3
y 4
z 5
0

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)))
0

Simply, use select with column slicing:

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.