Vincenzo
Vincenzo

Reputation: 365

I want to names dataframe's columns using a vector

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

Upvotes: 1

Views: 82

Answers (2)

Quinten
Quinten

Reputation: 41225

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

Upvotes: 1

akrun
akrun

Reputation: 886998

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

Upvotes: 1

Related Questions