R:使用paste()定义列名 [英] R: Define column name with paste()
问题描述
这个问题很简单,但是我找不到解决方案。
The question is pretty simple but I couldn't find a solution.
我想创建一个新的数据框,用<$ c $定义列的名称c> paste0 。
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') ="
为什么不起作用?
推荐答案
Data.frame
是一个函数,因此带有参数。这些参数不能是其他函数,例如,您不能定义类似 fn<-的函数-function(paste0('Hi_','how_are_you')= x){x}
。R只是无法正常工作。
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.
但是,您仍然可以动态更改col事实之后的数字名称:
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'))
这应该做您想要的事。
奖金:您可以按如下所示简化粘贴操作: paste('这里','我','列','名称',sep ='_')
。
Bonus: You can simplify your paste as follows: paste('Here', 'my', 'column', 'name', sep = '_')
.
这篇关于R:使用paste()定义列名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!