R use write.table to output contents to .txt file with specified width left align
时间: 2024-03-05 08:54:59 浏览: 78
To use `write.table` to output contents to a .txt file with specified width and left alignment, you can use the `format` argument with the `sprintf` function to format the text. Here's an example:
```r
# create a data frame
df <- data.frame(
name = c("Alice", "Bob", "Charlie"),
age = c(25, 30, 35),
salary = c(50000, 60000, 70000)
)
# open a connection to a file
con <- file("output.txt", "w")
# specify the format string
fmt <- "%-10s %-5d %-10d\n"
# write the header row
writeLines(sprintf(fmt, "Name", "Age", "Salary"), con)
# write the data rows
for (i in seq_len(nrow(df))) {
row <- df[i, ]
writeLines(sprintf(fmt, row$name, row$age, row$salary), con)
}
# close the connection
close(con)
```
In this example, the `fmt` string specifies the format for each row of data. The `-` sign before the width specifier `-10s` and `-10d` means that the text should be left-aligned. You can adjust the width and formatting to suit your needs.
阅读全文