如何阻止R将X预先添加到我的数字列标签中?(How do I stop R from prepending X to my numeric column labels?)

编程入门 行业动态 更新时间:2024-10-26 18:29:03
如何阻止R将X预先添加到我的数字列标签中?(How do I stop R from prepending X to my numeric column labels?)

我有一个带有数字列标签的矩阵,例如:

1,2,3 1,2,3 4,5,6 7,8,9

当我使用as.matrix(read.table("myfile", sep=",", header=TRUE)将此数据加载到R中的变量并打印生成的矩阵时,列标题已添加到X前面,这样额外字符出现在图表等中:

X1 X2 X3 [1,] 1 2 3 [2,] 4 5 6 [3,] 7 8 9

我怎么能阻止这种行为?

I have a matrix with numeric column labels, for example:

1,2,3 1,2,3 4,5,6 7,8,9

When I load this data into a variable in R using as.matrix(read.table("myfile", sep=",", header=TRUE) and print the resulting matrix, the column headers have been prepended with X, and this extra character appears in plots and the like:

X1 X2 X3 [1,] 1 2 3 [2,] 4 5 6 [3,] 7 8 9

How can I stop this behaviour?

最满意答案

为read.table提供check.names=FALSE 。

请注意,当data.frame具有非标准名称(例如此名称)时,对其列的任何引用都必须用刻度标记包围,例如

my.df <- read.table(text='1,2,3 1,2,3 4,5,6 7,8,9', header=TRUE, sep=',', check.names=FALSE) my.df$`1` with(my.df, `1`) attach(k) `1`

另外, transform调用(如transform(my.df, 1 =1:3)将用它们的标准化表单( X1 , X2 , X3 )替换列名称,因为transform使用其默认参数调用data.frame() 。

设置check.names=FALSE ,虽然在某些特定情况下很有用,但会允许重复的列名和非语法名,这可能会导致以后出现任何问题。 使用时要小心。

data.frame()默认使用check.names=TRUE ,因为在很多上下文中,R试图将数据框的列名解释为变量; 如果列名不是语法上有效的名称(请参阅?make.names ),或者如上所述使用back-ticks保护,则在这些上下文中将出现错误。

Supply check.names=FALSE to read.table.

Be aware that when data.frames have non-standard names such as this any reference to their columns must be surrounded with tick marks, e.g.

my.df <- read.table(text='1,2,3 1,2,3 4,5,6 7,8,9', header=TRUE, sep=',', check.names=FALSE) my.df$`1` with(my.df, `1`) attach(k) `1`

Also, calls to transform, such as transform(my.df,1=1:3), will replace the column names with their standardized forms (X1, X2, X3) because transform calls data.frame() with its default arguments.

Setting check.names=FALSE, while useful in some very particular situations, will allow duplicate column names and non syntactic names, which could cause any number of problems later on. Be cautious when using this.

data.frame() uses check.names=TRUE by default because in many contexts R tries to interpret the column names of a data frame as variables in their own right; if the column names are not syntactically valid names (see ?make.names), or protected with back-ticks as described above, then errors will occur in these contexts.

更多推荐

本文发布于:2023-08-07 14:06:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1464905.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:标签   数字   stop   prepending   column

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!