Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Keep column name when select one column from a data frame/matrix in R

Tags:

r

In R, when I select only one column from a data frame/matrix, the result will become a vector and lost the column names, how can I keep the column names? For example, if I run the following code,

x <- matrix(1,3,3)
colnames(x) <- c("test1","test2","test3")
x[,1]

I will get

[1] 1 1 1

Actually, I want to get

     test1
[1,]     1
[2,]     1
[3,]     1

The following code give me exactly what I want, however, is there any easier way to do this?

x <- matrix(1,3,3)
colnames(x) <- c("test1","test2","test3")
y <- as.matrix(x[,1])
colnames(y) <- colnames(x)[1]
y
like image 715
user17670 Avatar asked Mar 29 '15 04:03

user17670


People also ask

How do I select one column from a Dataframe in R?

To select a column in R you can use brackets e.g., YourDataFrame['Column'] will take the column named “Column”. Furthermore, we can also use dplyr and the select() function to get columns by name or index. For instance, select(YourDataFrame, c('A', 'B') will take the columns named “A” and “B” from the dataframe.

How do I label a column in a matrix in R?

We use colnames() function for renaming the matrix column in R. It is quite simple to use the colnames() function. If you want to know more about colnames() function, then you can get help about it in R Studio using the command help(colnames) or ? colnames().

How do I extract column names from a Dataframe in R?

To access a specific column in a dataframe by name, you use the $ operator in the form df$name where df is the name of the dataframe, and name is the name of the column you are interested in. This operation will then return the column you want as a vector.


2 Answers

Use the drop argument:

> x <- matrix(1,3,3)
> colnames(x) <- c("test1","test2","test3")
> x[,1, drop = FALSE]
     test1
[1,]     1
[2,]     1
[3,]     1
like image 67
A5C1D2H2I1M1N2O1R2T1 Avatar answered Oct 25 '22 15:10

A5C1D2H2I1M1N2O1R2T1


Another possibility is to use subset:

> subset(x, select = 1)

     test1
[1,]     1
[2,]     1
[3,]     1
like image 39
Dominic Comtois Avatar answered Oct 25 '22 14:10

Dominic Comtois