improve the code as the it gets error "Error in sprintf(fmt, "Name", "Age", "Salary") : invalid format '%-5d'; use format %s for character objects"
时间: 2023-07-13 12:30:58 浏览: 171
Thank you for letting me know about the error message. The issue is that the format string `%d` is used for integers, but you're trying to format column headers, which are character strings. To fix this, you can replace `%d` with `%s` in the format string for the header row. Here's the updated code:
```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 %-5s %-10s\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 updated code, the format string `%s` is used instead of `%d` for the header row. This will format the column headers as character strings, which is what they are.
阅读全文