简体   繁体   中英

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

I am importing a csv of stock data into R, with column names of stock ticker which starts with number and containing space inside, eg "5560 JP". After reading into R, the column names are added with "X" and space replaced by ".", eg "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, eg "5560 JP" instead of "X5560.JP", how can I do that?

Thank you!

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM