在 data.frame 中指定列名称会将空格更改为“.”
假设我有一个 data.frame,如下所示:
x <- c(1:10,1:10,1:10,1:10,1:10,1:10,1:10,1:10,1:10,1:10)
df <- data.frame("Label 1"=x,"Label 2"=rnorm(100))
head(df,3)
returns:
Label.1 Label.2
1 1 1.9825458
2 2 -0.4515584
3 3 0.6397516
如何让 R 停止自动用列名中的句点替换空格?即“Label 1”而不是“Label.1”。
Let's say I have a data.frame, like so:
x <- c(1:10,1:10,1:10,1:10,1:10,1:10,1:10,1:10,1:10,1:10)
df <- data.frame("Label 1"=x,"Label 2"=rnorm(100))
head(df,3)
returns:
Label.1 Label.2
1 1 1.9825458
2 2 -0.4515584
3 3 0.6397516
How do I get R to stop automagically replacing the space with a period in the column name? ie, "Label 1" instead of "Label.1".
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您可以在
data.frame
(以及read.table
)中设置check.names = FALSE
:returns:
From
?数据.frame
:来自
?make.names
:此外,如果您需要使用
$
对名称为“无效”的变量进行子集化,则可以使用反引号`< /代码>。例如:
You may set
check.names = FALSE
indata.frame
(as well as inread.table
):returns:
From
?data.frame
:From
?make.names
:Also, if you need to subset a variable with an 'invalid' name using
$
, you can use backticks`
. For example:你不知道。
对于您想要的空格,该格式无法满足使用
df$column.1
时发挥作用的标识符的要求——无法处理空格。因此,请参阅make.names()
函数了解详细信息或示例:十一年后编辑:答案仍然是 R 更喜欢列名可以是有效的变量名。但 R 很灵活:如果您坚持使用其他形式,但需要明确要求语言内无效的列名称:
因此,可以说
check.names=FALSE
我们覆盖默认(且合理)的检查,并通过将标识符括在反引号中,我们可以访问该列。You don't.
With the space you desire the format would not satisfy the requirements for an identifier that come to play when you use
df$column.1
-- that could not cope with a space. So see themake.names()
function for details or an example:Edit eleven years later: The answer still stands that R prefers column names can be valid variable names. But R is flexible: if you insist you can use the other form _but then need to require the not-otherwise-valid-within-the-language column names explicitly:
So by saying
check.names=FALSE
we override the default (and sensible) check, and by wrapping the identifier in backticks we can access the column.您可以更改现有数据框名称以包含空格,即使用示例
返回
,并且您仍然可以使用 $ 运算符访问列,您只需要使用双引号,例如
返回
对我来说,自动转换列名似乎相当不一致data.frame 创建,但在列名更改期间不执行相同操作,但这就是 R 目前的工作方式。
You can change an existing data frames names to contain spaces ie using your example
returns
and you can still access the columns using the $ operator, you just need to use double quotes eg
returns
It seems rather inconsistent to me to auto-convert column names upon data.frame creation, but not to-do the same during column name alteration, but thats how R works at the moment.