Home > Mobile >  How to name the columns of a vector in R?
How to name the columns of a vector in R?

Time:10-07

I tried to put a matrix to place names but it does not start.

  • Create a vector named "sales" with 120, 140, 90 and 196.
  • Assign names to the columns of the vector "January", "February", "March", "April".

CodePudding user response:

You have a couple issues here. To start with, a vector is one-dimensional, so it doesn't have columns. You can assign names to the values of a vector. To do that you would use

> Sales <- c(120, 140, 90, 196)
> names(Sales) <- c("January", "February", "March", "April")
> Sales
 January February    March    April 
     120      140       90      196 
> dim(Sales)
NULL
> colnames(Sales)
NULL

In your example you have Sales capitalized when you assign it, but not when you try to assign names. This would return an error because sales does not exist, but Sales does.

You need columns to assign column names

> as.data.frame(Sales)
         Sales
January    120
February   140
March       90
April      196

> m = matrix(Sales, nrow = 1)
> m
     [,1] [,2] [,3] [,4]
[1,]  120  140   90  196

### m has columns, so you can now

colnames(m) <- c("January", "February", "March", "April")

> m
     January February March April
[1,]     120      140    90   196
  •  Tags:  
  • r
  • Related