Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R - column names in read.table and write.table starting with number and containing space

Tags:

r

I am importing a csv of stock data into R, with column names of stock ticker which starts with number and containing space inside, e.g. "5560 JP". After reading into R, the column names are added with "X" and space replaced by ".", e.g. "X5560.JP". After all the works are done in R, I want to write the processed data back to a new csv, but with the original column name, e.g. "5560 JP" instead of "X5560.JP", how can I do that?

Thank you!

like image 849
Joyce Avatar asked Jul 22 '12 00:07

Joyce


1 Answers

When you use write.csv or write.table to save your data to a CSV file, you can set the column names to whatever you like by setting the col.names argument.

But that assumes you have the column names to available. Once you've read in the data and R has converted the names, you've lost that information. To get around this, you can suppress the conversion to get the column names:

df <- read.csv("mydata.csv", check.names=FALSE)
orig.cols <- colnames(df)
colnames(df) <- make.names(colnames(df))

[your original code]

write.csv(df, col.names=orig.cols)
like image 139
seancarmody Avatar answered Oct 21 '22 07:10

seancarmody