我有一个带有数字列标签的矩阵,例如:
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,9When 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 9How 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.
更多推荐
发布评论