Jason
Jason

Reputation: 1569

Set up column names in a new data frame based on variable

My goal is to be able to allocate column names to a data frame that I create based on a passed variable. For instance:

i='column1'

data.frame(i=1)
  i
1 1

Above the column name is 'i' when I want it to be 'column1'. I know the following works but isn't as efficient as I'd like:

i='column1'
df<-data.frame(x=1)
setnames(df,i)
  column1
1       1

Upvotes: 2

Views: 134

Answers (5)

armoschiano
armoschiano

Reputation: 119

You could simply pass the name of your column variable and its values as arguments to a dataframe, without adding more lines:

df <- data.frame(column1=1)
df
#  column1
#1       1

Upvotes: 0

Draguru
Draguru

Reputation: 11

Not exactly sure how you want it more efficient but you could add all the column names at once after your data frame has been assembled with colnames. Here's an example based on yours.

data.frame(Td) a b 1 1 4 2 1 5

nam<-c("Test1","Test2") colnames(Td)<-nam

data.frame(Td) Test1 Test2 1 1 4 2 1 5

Upvotes: 0

N8TRO
N8TRO

Reputation: 3364

It's good to learn how base R works this way:

i  <- 'cloumn1'
df <- `names<-`(data.frame(1), i)
df
#  cloumn1
#1       1

Upvotes: 2

dmp
dmp

Reputation: 825

Aside from the answers posted by other users, I think you may be stuck with the solution you've already presented. If you already have a data frame with the intended number of rows, you can add a new column using brackets:

df <- data.frame('column1'=1)
i <- 'column2'
df[[i]] <- 2
df
column1 column2
1       2

Upvotes: 2

Rorschach
Rorschach

Reputation: 32466

If the idea is to get rid of the setNames, you would probably never do this but

i <- 'column1'
data.frame(`attr<-`(list(1), "names", i))
#   column1
# 1       1

You can see in data.frame, it has the code

x <- list(...)
vnames <- names(x)

so, you can mess with the name attribute.

Upvotes: 1

Related Questions