Reputation: 166
I'm trying to name a vector with only a single column, i.e. say I have
vector<-c(1,2,3,4)
I want to name a single column of (1,2,3,4) as "a", i.e. I want something like:
a
1
2
3
4
If I try
colnames(vector)<- c("a")
It gives me output:
Error in `colnames<-`(`*tmp*`, value = "a") :
attempt to set 'colnames' on an object with less than two dimensions
If I try
names(vector)<- c("a")
Vector is named as
a <NA> <NA> <NA>
1 2 3 4
My question is if such a vector is allowed in R? Specifically, is this allowed without using a matrix or data.frame or any other such class which can store more than one columns? If yes, how do I create it?
Upvotes: 0
Views: 1306
Reputation: 263471
If you want something with a column name and that will print in the column format then use a single column matrix
or data.frame
:
vector <- matrix( c(1,2,3,4), dimnames=list(NULL, "a") )
vector <- data.frame( a=c(1,2,3,4) )
There is a 1d object type but rather confusingly it requires that the assignment of a single dimension value to be its length. See:
?dim
dim(vector)=1L
Error in dim(vector) = 1L :
dims [product 1] do not match the length of object [4]
> dim(vector)=4L
> vector
[1] 1 2 3 4
> str(vector)
num [1:4(1d)] 1 2 3 4
Actually the dim function help page doesn't appear to document the requirement that the product of the dim-result will equal the length. My guess is that your homework assignment was intended to get you to read the dim help page and then discover (as I just did) that a one-d object is possible but a bit confusing.
As it turns out the distinction between row and column vectors is not enforced:
> vector %*% matrix(1:16,4)
[,1] [,2] [,3] [,4]
[1,] 30 70 110 150
> t(vector) %*% matrix(1:16,4)
[,1] [,2] [,3] [,4]
[1,] 30 70 110 150
> t(vector) %*% matrix(1:16,4) %*% vector
[,1]
[1,] 1100
> vector %*% matrix(1:16,4) %*% vector
[,1]
[1,] 1100
Upvotes: 2