简体   繁体   English

R 粘贴使用循环

[英]R paste using a loop

I am generating an input file for software.我正在为软件生成一个输入文件。 I ran into an inconsistency in paste0() function.我在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 ";"此 function 没有正确使用","以及";" at the end.在最后。

Any thoughts?有什么想法吗? Thanks.谢谢。

We could do this without a loop as paste is vectorized我们可以在没有循环的情况下执行此操作,因为paste是矢量化的

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.您不能像这样使用 for 循环“扩展”到 function arguments 中。 Especially not by trying to print them.尤其是不要试图print它们。 This isn't Bash.这不是 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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM