[英]R: Define column name with paste()
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
. 我想创建一个新的数据
paste0
用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? 另外,为什么不起作用?
Data.frame
is a function, and therefore takes arguments. Data.frame
是一个函数,因此接受参数。 These arguments cannot be other functions. 这些参数不能是其他函数。 For example, you could not define a function like
fn <- function(paste0('Hi_', 'how_are_you') = x) { x }
. 例如,您无法定义函数,如
fn <- function(paste0('Hi_', 'how_are_you') = x) { x }
。 R just doesn't work that way. R就是这样不行。
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 = '_')
. 奖励:您可以按如下方式简化粘贴:
paste('Here', 'my', 'column', 'name', sep = '_')
。
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. 这样,
paste('Here', 'my', 'column', 'name', sep = '_')
将被评估,返回的字符串实际上将用作列的名称。
I needed the same some time ago and solved the problem with putting all the command inside paste function with following evaluation 前段时间我需要同样的东西,并通过以下评估将所有命令放入粘贴功能中解决了问题
i=3
mydf <- eval(parse(text = paste0(
"data.frame( id =", 1, ", my_col", i, "=", 55, ")")))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.