gpt4 book ai didi

r - 在 data.frame 中指定列名将空格更改为 "."

转载 作者:行者123 更新时间:2023-12-01 18:18:10 24 4
gpt4 key购买 nike

假设我有一个 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))

头(df,3)

返回:

  Label.1    Label.2
1 1 1.9825458
2 2 -0.4515584
3 3 0.6397516

如何让 R 停止自动用列名中的句点替换空格?即“Label 1”而不是“Label.1”。

最佳答案

您可以在data.frame(以及read.table)中设置check.names = FALSE:

df <- data.frame("Label 1" = 1:3, "Label 2" = rnorm(3), check.names = FALSE)

返回:

  Label 1    Label 2
1 1 0.2013347
2 2 1.8823111
3 3 -0.5233811
<小时/>

来自?data.frame:

check.names
logical. If TRUE then the names of the variables in the data frame are checked to ensure that they are syntactically valid variable names and are not duplicated. If necessary they are adjusted (by make.names) so that they are.

<小时/>

来自 ?make.names:

A syntactically valid name consists of letters, numbers and the dot or underline characters and starts with a letter or the dot not followed by a number. Names such as ".2way" are not valid, and neither are the reserved words.

All invalid characters are translated to "."

<小时/>

此外,如果您需要使用 $ 对名称为“无效”的变量进行子集化,则可以使用反引号 `。例如:

df$`Label 1`

关于r - 在 data.frame 中指定列名将空格更改为 ".",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3411201/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com