Ali
Ali

Reputation: 9850

How to name a column while creating a data frame using a name stored in a variable?

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?

Upvotes: 4

Views: 6251

Answers (4)

Jai
Jai

Reputation: 321

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

Upvotes: 0

Dan Gerlanc
Dan Gerlanc

Reputation: 417

Try:

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

Upvotes: 2

A5C1D2H2I1M1N2O1R2T1
A5C1D2H2I1M1N2O1R2T1

Reputation: 193687

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

Upvotes: 11

Gavin Simpson
Gavin Simpson

Reputation: 174948

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

Upvotes: 5

Related Questions