Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R: Define column name with paste()

Tags:

dataframe

r

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?

like image 657
CptNemo Avatar asked Apr 19 '15 16:04

CptNemo


People also ask

How do you set column names in R?

Method 1: using colnames() method colnames() method in R is used to rename and replace the column names of the data frame in R. The columns of the data frame can be renamed by specifying the new column names as a vector. The new name replaces the corresponding old name of the column in the data frame.

How do I reference a column in R?

We reference a data frame column with the double square bracket "[[]]" operator. For example, to retrieve the ninth column vector of the built-in data set mtcars, we write mtcars[[9]].


2 Answers

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 = '_').

like image 75
peterhurford Avatar answered Oct 08 '22 15:10

peterhurford


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
like image 21
GKi Avatar answered Oct 08 '22 17:10

GKi