I want to name dataframe's columns using a vector of character. I don't know why with the following code I get the error:
Error in names(x) <- value : 'names' attribute [5] must be the same length as the vector [1]
vec <- 1:5
vec <- as.data.frame(vec)
colnames(vec) <- c("a", "b", "c", "d", "e")
Thanks in advance
CodePudding user response:
You can use this code:
vec <- 1:5
vec <- as.data.frame(t(vec))
colnames(vec) <- c("a", "b", "c", "d", "e")
Output:
a b c d e
1 1 2 3 4 5
CodePudding user response:
The as.data.frame
still returns a single column. Instead, we may need to use as.data.frame.list
vec <- 1:5
vec <- as.data.frame.list(vec)
colnames(vec) <- c("a", "b", "c", "d", "e")
-output
> vec
a b c d e
1 1 2 3 4 5