R: Define column name with paste()

14,803

Solution 1

Data.frame is a function, and therefore takes arguments. These arguments cannot be other functions. For example, you could not define a function like fn <- function(paste0('Hi_', 'how_are_you') = x) { x }. R just doesn't work that way.

However, you still can dynamically change your column names after the fact:

df <- data.frame(1, 'foo')
names(df) <- c('id', paste0('Here_','my_','column_','name'))

That should do what you want.

Bonus: You can simplify your paste as follows: paste('Here', 'my', 'column', 'name', sep = '_').

Solution 2

You can use setNames to define column names of a data.frame with paste() - dynamically specify the column name

setNames(data.frame(1, 'foo'), c("id",  paste0('Here_','my_','column_','name')))
#  id Here_my_column_name
#1  1                 foo

Solution 3

You can do

df[, paste('Here', 'my', 'column', 'name', sep = '_')] <- 'foo'

It is impossible to do it as you suggest, because no variable is evaluated, it just gets exactly what you are writing and trying to use it as a name for the column. This way, paste('Here', 'my', 'column', 'name', sep = '_') gets evaluated and the returned string is actually used as a name for the column.

Share:
14,803

Related videos on Youtube

CptNemo
Author by

CptNemo

Updated on September 15, 2022

Comments

  • CptNemo
    CptNemo over 1 year

    The question is pretty simple but I couldn't find a solution.

    I want to create a new dataframe defining the name of the column with paste0.

    Ideally I would like to do something like this (which of doesn't work).

    mydataframe <- data.frame(id = 1,
                              paste0('Here_','my_','column_','name') = 'foo')
    # Error: unexpected '=' in:
    #   "mydataframe <- data.frame(id = 1,
    #                           paste0('Here_','my_','column_','name') ="
    

    Also, why doesn't work?

    • nrussell
      nrussell about 9 years
      @BrianP I think what he wants is to be able to dynamically specify the name associated with the column vector 'foo', so the result would be equivalent to manually typing data.frame(id = 1, Here_my_column_name = 'foo').
    • Brian P
      Brian P about 9 years
      Ahhh, makes sense! Thx for the clarification