[R] Col names in a data frame

Duncan Murdoch
Thu, 21 Jan 2021 21:14:33 -0000

On 21/01/2021 3:58 p.m., Bernard McGarvey wrote:
> Here is an example piece of code to illustrate an issue:
>
> rm(list=ls()) # Clear Workspace
> #
> Data1 <- matrix(data=rnorm(9,0,1),nrow=3,ncol=3)
> Colnames1 <- c("(A)","(B)","(C)")
> colnames(Data1) <- Colnames1
> print(Data1)
> DataFrame1 <- data.frame(Data1)
> print(DataFrame1)
> colnames(DataFrame1) <- Colnames1
> print(DataFrame1)
>
> The results I get are:
>
>              (A)        (B)        (C)
> [1,]  0.4739417  1.3138868  0.4262165
> [2,] -2.1288083  1.0333770  1.1543404
> [3,] -0.3401786 -0.7023236 -0.2336880
>          X.A.       X.B.       X.C.
> 1  0.4739417  1.3138868  0.4262165
> 2 -2.1288083  1.0333770  1.1543404
> 3 -0.3401786 -0.7023236 -0.2336880
>           (A)        (B)        (C)
> 1  0.4739417  1.3138868  0.4262165
> 2 -2.1288083  1.0333770  1.1543404
> 3 -0.3401786 -0.7023236 -0.2336880
>
> so that when I make the matrix with headings the parentheses are replaced
by periods but I can add them after creating the data frame and the column
headings are correct.
>
> Any ideas on why this occurs?

By default, data.frame() uses names that are legal variable names, so
you can do things like Data1$X.A. You can stop this change by saying

DataFrame1 <- data.frame(Data1, check.names=FALSE)

Duncan Murdoch