4

Trying to create a data.frame like this:

a = "foo"
bar = data.frame(a = 1:3)

But the name of the column is a, not foo:

> bar
  a
1 1
2 2
3 3

The column can be renamed after creating data.frame, but how to easily assign it's name by a variable just in the same data.frame command?

4 Answers 4

11

The setNames() function should work for you:

a <- "Numbers"
b <- "Letters"

bar <- setNames(data.frame(1:3, letters[1:3]), c(a, b))
bar
#   Numbers Letters
# 1       1       a
# 2       2       b
# 3       3       c
Sign up to request clarification or add additional context in comments.

2 Comments

Great! Thanks for it. Do you have any idea how to do the task if we are making a data.frame of several tables or vectors and we want a few of them to be named by variables: data.frame(a = 1:3, b) while b is a table and we are not going to change the names of b columns?
@AliSharifi, when you write "b is a table", do you actually mean table or data.frame? If b is a data.frame, you could just use setNames(data.frame(1:3, b), c(a, names(b))) (if I understood your question correctly).
5

I don't think you can do what you want to do here because of the way R is interpreting the argument names you supply. Effectively you want get(a) = 1:3 as you want R to take the value of the object stored as a rather than the label a itself, but that idiom is not allowed here.

I would do this:

> a <- "foo"
> bar <- data.frame(1:3)
> names(bar) <- a
> 
> bar
  foo
1   1
2   2
3   3

9 Comments

Thanks, I already know this solution. I am looking for a one-line command to do it!
If you insist: bar <- `names<-`(data.frame(1:3),a)
@AliSharifi Don't always be on the look-out for a one-liner. Two are just as useful and easier to write. Think about how much time you have spent on this to save a single R call?
@GavinSimpson, there is, of course the "convenience function" setNames().
@GavinSimpson I'm a bit way of using `names<-`, but I'm not sure why it's not recommended.
|
2

Try:

a = structure(data.frame(1:3), names="foo")
> a
foo
1   1
2   2
3   3

Comments

0

Slight modification of Daniel Gerlanc's answer using chaining

a <- "foo"
a <- data.frame(1:3) %>% structure(names = c(a))

  foo
1   1
2   2
3   3

Chaining is useful when you are creating a data frame from another data type, for example a zoo series,

a <- c("foo","data")
bar
2016-01-01 2016-01-02 2016-01-03 2016-01-04 2016-01-05 
      0.78       0.46       0.82       1.07       1.04


a <- bar %>% as.data.frame() %>% tibble::rownames_to_column() %>% structure(names=a)

          foo data
1  2016-01-01 0.78
2  2016-01-02 0.46
3  2016-01-03 0.82
4  2016-01-04 1.07
5  2016-01-05 1.04

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.