当r中有特殊字符时写出一个字符值插入缩进

writing out a character value inserting indentation when there is special character in r

我正在研究字符值,我需要将它们写出来。这是我的示例值的样子:

items <- c("A1","A2","A3","A4","A5")
group <- c(paste0("Items = ",paste0(items, collapse=", "), ";"), #Items
           paste0(paste0("Codes(", items, ") = 0(0), 1(1)",collapse="; ", sep=""),";"), #Codes
           paste0(paste("Model(", items, ") = 2PL",collapse="; ", sep=""),";"))

> group
[1] "Items = A1, A2, A3, A4, A5;"                                                                                            
[2] "Codes(A1) = 0(0), 1(1); Codes(A2) = 0(0), 1(1); Codes(A3) = 0(0), 1(1); Codes(A4) = 0(0), 1(1); Codes(A5) = 0(0), 1(1);"
[3] "Model(A1) = 2PL; Model(A2) = 2PL; Model(A3) = 2PL; Model(A4) = 2PL; Model(A5) = 2PL;"    

cat(group, file = "test.irtpro")

当我写出来的时候,所有的东西都在一条线上。但是,当末尾有 ; 时,我需要一个缩进。所以写在输出文件中的期望输出应该是:

Items = A1, A2, A3, A4, A5;                                                                                            
Codes(A1) = 0(0), 1(1); 
Codes(A2) = 0(0), 1(1); 
Codes(A3) = 0(0), 1(1); 
Codes(A4) = 0(0), 1(1); 
Codes(A5) = 0(0), 1(1);
Model(A1) = 2PL; 
Model(A2) = 2PL; 
Model(A3) = 2PL; 
Model(A4) = 2PL; 
Model(A5) = 2PL;

关于如何实现这一点有什么想法吗?

谢谢

也许你可以试试:

cat(unlist(strsplit(group, "(?<=;\s)", perl = TRUE)), file = "test.irtpro", sep = "\n")

这将按分号拆分字符串(保留分号,但之后省略 space),并在每次拆分时使用换行符 \n

test.irtpro

Items = A1, A2, A3, A4, A5;
Codes(A1) = 0(0), 1(1); 
Codes(A2) = 0(0), 1(1); 
Codes(A3) = 0(0), 1(1); 
Codes(A4) = 0(0), 1(1); 
Codes(A5) = 0(0), 1(1);
Model(A1) = 2PL; 
Model(A2) = 2PL; 
Model(A3) = 2PL; 
Model(A4) = 2PL; 
Model(A5) = 2PL;