R语言中如何在字符与数值组合条目后添加换行?
Got it, let's break down why your current code is causing labels and values to split across lines, then walk through a few straightforward fixes.
Why Your Original Code Isn't Working
Your current paste() call passes every label and numeric value as a separate argument, then uses sep='\n' to put a line break between every single argument. That means:
"Student Id:"gets a line break after it, separating it fromV1"Number of circuts:"gets a line break after it, separating it fromV2
And so on—exactly the issue you're seeing.
Solution 1: Combine Labels + Values First, Then Add Line Breaks
The fix here is to first build each complete "label + value" pair as a single string, then join those pairs with line breaks using collapse='\n':
V1 <- 81 V2 <- 55 V3 <- 25 cat(paste( paste("Student Id:", V1), # Builds "Student Id: 81" paste("Number of circuts:", V2), # Builds "Number of circuts: 55" paste("Time (Minutes):", V3), # Builds "Time (Minutes): 25" collapse = '\n' # Joins the three strings with line breaks ))
This will output exactly what you want:
Student Id: 81
Number of circuts: 55
Time (Minutes): 25
Solution 2: Use sprintf() for Clean Formatting
If you prefer a more concise approach, sprintf() lets you define a single template with placeholders for your values, and you can insert line breaks directly into the template:
V1 <- 81 V2 <- 55 V3 <- 25 cat(sprintf( "Student Id: %d\nNumber of circuts: %d\nTime (Minutes): %d", V1, V2, V3 ))
Here, %d is a placeholder for integer values (use %f for decimals if needed), and \n adds the line breaks exactly where you want them.
Solution 3: Use the glue Package for Intuitive String Interpolation
If you don't mind using a third-party package, glue makes string formatting super readable—you can just reference variables directly in the string and add line breaks naturally:
library(glue) V1 <- 81 V2 <- 55 V3 <- 25 cat(glue("Student Id: {V1} Number of circuts: {V2} Time (Minutes): {V3}"))
No extra paste calls needed—just write the text exactly how you want it to appear, with {} wrapping your variables.
内容的提问来源于stack exchange,提问作者Luis Mompó




