在R语言中读写.dat文件时保持原始格式的解决方案
Hey there! The issue you're running into is that write.csv() forces comma-separated values, which completely changes the whitespace-separated format of your original .dat file. Instead, you'll want to use write.table()—it gives you full control over the output format to match your original file.
Let's break this down step by step:
1. First, Ensure Proper Import
Make sure you're reading the original file correctly to capture its structure. Since your file uses spaces as separators (and likely handles multiple spaces cleanly), read.table() is a better fit than read.delim() (which defaults to tab-separated values):
# Import the original .dat file correctly Tin <- read.table("your_original_file.dat", header = TRUE, sep = " ", # Use space as separator strip.white = TRUE, # Remove extra whitespace between values stringsAsFactors = FALSE)
2. Modify Your Data As Needed
Make whatever changes you need to the Tin object—this part stays the same as your current workflow.
3. Save with write.table() to Match Original Format
Use write.table() with parameters tailored to your original file's structure. Here's the exact code to replicate your sample format:
write.table(Tin, file = "TinNew.dat", sep = " ", # Match original space-separated values row.names = FALSE, # Original file has no row numbers—exclude them col.names = TRUE, # Keep the header row quote = FALSE, # Don't add quotes around values (original has none) na = "", # Handle missing values as empty strings (adjust if needed) digits = 5) # Match the decimal precision from your sample (5 digits where needed)
Fine-Tuning Numeric Formatting
If you need mixed formatting (like integers for the Time [d] column and 5-digit decimals for T_in [degC]), you can pre-format each column before saving:
# Format Time as integers Tin$`Time [d]` <- formatC(Tin$`Time [d]`, format = "d") # Format T_in with 5 decimal places Tin$`T_in [degC]` <- formatC(Tin$`T_in [degC]`, format = "f", digits = 5) # Now save with write.table()—you can omit the `digits` parameter here since we pre-formatted write.table(Tin, file = "TinNew.dat", sep = " ", row.names = FALSE, col.names = TRUE, quote = FALSE)
This will produce a file that looks identical to your original .dat file in any text editor.
内容的提问来源于stack exchange,提问作者Tim Adams

