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?
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.
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]].
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 = '_')
.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With