Gene Gene - 18 days ago 6
R Question

Problems with column names in R

I am new to R. I am trying to use the "write.csv" command to write a csv file in R. Unfortunately, when I do this, the resulting data frame produces colnames with a prefix X in it eventhough the file already has a column name.

It produces, X_name1 ,X_name2

Please kindly tell me your suggestions

I have added an example code similar to my data.

a<- c("1","2")
b <- c("3","4")
df <- rbind(a,b)
df <- as.data.frame(df)
names(df) <- c("11_a","12_b")
write.csv(df,"mydf.csv")
a <- read.csv("mydf.csv")
a

#Result
X X11_a X12_b
1 a 1 2
2 b 3 4


All I need is to have only "11_a" and "12_b" as column names. But it incudes prefix X also.

Answer

Use check.names=FALSE when reading your data back in - names starting with numbers are not generally acceptable in R:

read.csv(text="11_a,12_b
a,1,2
b,3,4", check.names=FALSE)

#  11_a 12_b
#a    1    2
#b    3    4

read.csv(text="11_a,12_b
a,1,2
b,3,4", check.names=TRUE)

#  X11_a X12_b
#a     1     2
#b     3     4
Comments