简体   繁体   中英

R paste using a loop

I am generating an input file for software. I ran into an inconsistency in paste0() function. Here are my example list of names.

vars <- c("1234_AS_SA1_PCNS","2345_AS_SA2_UDA", "3823_AS_SA3_CL")

I would like to print this:

 "Equal = (1234_AS_SA1_PCNS, Slope[0]),
          (2345_AS_SA2_UDA, Slope[0]),
          (3823_AS_SA3_CL, Slope[0]);"

I tried this but it did not do the job. SOmehow, "Equal" gets to the end.

paste0("Equal = ", 
       
       for(i in 1:length(vars)) {
         Equal <- paste0("(",vars[i], ", Slope[0])", ",")
         print(Equal)
       })


[1] "(1234_AS_SA1_PCNS, Slope[0]),"
[1] "(2345_AS_SA2_UDA, Slope[0]),"
[1] "(3823_AS_SA3_CL, Slope[0]),"
[1] "Equal = "

This function does not employ "," s correctly as well as a ";" at the end.

Any thoughts? Thanks.

We could do this without a loop as paste is vectorized

cat(paste0("Equal = ", paste("(", vars, ", Slope[0])",
        collapse=",\n ", sep=""), ";"))
Equal = (1234_AS_SA1_PCNS, Slope[0]),
 (2345_AS_SA2_UDA, Slope[0]),
 (3823_AS_SA3_CL, Slope[0]);

If we need to have double quotes at the end

cat(dQuote(paste0("Equal = ", paste("(", vars, ", Slope[0])",
        collapse=",\n ", sep=""), ";"), FALSE))
"Equal = (1234_AS_SA1_PCNS, Slope[0]),
 (2345_AS_SA2_UDA, Slope[0]),
 (3823_AS_SA3_CL, Slope[0]);"

Or may be

cat(dQuote(paste0("Equal = ", paste(sprintf('"(%s, Slope[0])"', vars), collapse=",\n ", sep="")), FALSE))
"Equal = "(1234_AS_SA1_PCNS, Slope[0])",
 "(2345_AS_SA2_UDA, Slope[0])",
 "(3823_AS_SA3_CL, Slope[0])""

You can't use a for loop to "expand" into function arguments like that. Especially not by trying to print them. This isn't Bash.

vars <- c("1234_AS_SA1_PCNS","2345_AS_SA2_UDA", "3823_AS_SA3_CL")

# Generate each "(<var>, Slope[0])" section
sections <- as.list(paste0("(", vars, ", Slope[0])"))

# Join the sections with ", "
sections_str <- do.call(paste, c(sections, sep = ", "))

# Construct the final string
result <- paste0("Equal = ", part2)

print(result)

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