R中的字符串操作:如何使用cat(…,sep=";)打印,但忽略最后一个空格?
我用R打印一个MPLUS命令。我必须指定许多变量之间的协方差。因此,我必须创建集合的所有子集。在MPLUS,必须这样指定(如果我们考虑4个变量的女性、年龄、EDU移徙者的列表): 代表4个变量集合中大小为2的所有子集(女性随年龄增长;女性随教育程度增长;女性随移民增长;年龄随教育程度增长;年龄随移民增长;教育程度随移民增长;) 为了获得可以直接复制到MPLU中的输出,我使用命令cat()。不幸的是,我无法获得上面显示的输出,但只能获得此输出(请注意分号): 我玩了很多关于粘贴、猫和打印的游戏。但是,要么我得到一个在行尾分号前面有一个空格的输出(就像上面的一样),要么我得到:R中的字符串操作:如何使用cat(…,sep=";)打印,但忽略最后一个空格?,r,string,printing,cat,R,String,Printing,Cat,我用R打印一个MPLUS命令。我必须指定许多变量之间的协方差。因此,我必须创建集合的所有子集。在MPLUS,必须这样指定(如果我们考虑4个变量的女性、年龄、EDU移徙者的列表): 代表4个变量集合中大小为2的所有子集(女性随年龄增长;女性随教育程度增长;女性随移民增长;年龄随教育程度增长;年龄随移民增长;教育程度随移民增长;) 为了获得可以直接复制到MPLU中的输出,我使用命令cat()。不幸的是,我无法获得上面显示的输出,但只能获得此输出(请注意分号): 我玩了很多关于粘贴、猫和打印的游戏。但
female WITH ageedumigrant;
age WITH edumigrant;
edu WITH migrant;
所以我的问题基本上是:如何省略cat(…,sep=“”)命令中的最后一个空格
我的小函数如下所示:
library(stringr)
vars_b <- "female age edu migrant"
covstructure <- function(x, cov = TRUE, var = TRUE, width = 80) {
# decode variable list into a vector, e.g. x[1] = "female" #
x <- gsub("(?<=[\\s])\\s*|^\\s+|\\s+$", "", x, perl=TRUE)
x <- unlist(strsplit(x, " "))
# covariance structure (the part of interest here) #
if(cov==TRUE) {
# all combinations #
result <- combn(x,2)
# get subsets into the MPLUS format: #
# female WITH age edu migrant; #
# age WITH edu migrant; #
# edu WITH migrant; #
for(i in 1:(length(x)-1)) {
# indices of the combinations that include the i-th variable #
ind <- which(result==x[i])
# print variable WITH its combinations #
# here is my problem: #
cat(result[which.min(ind)], "WITH", result[ind+1], ";", fill=width)
# create new combinations without the combinations of preceding variables, i.e. 1 to i #
if(i < length(x)-1) { result <- combn(x[-c(1:i)],2) }
}
}
# variance structure (not of interest) #
if(var==TRUE) {
cat(x, "", sep="; ", fill=width)
}
}
covstructure(vars_b, cov=TRUE, var=FALSE)
库(stringr)
vars_b以下代码是否适用于您
x <- c("female", "WITH", "age", "edu", "migrant")
cat(cat(x), ";", sep="")
x这是一个很好的方法-
x <- c("female", "WITH", "age", "edu", "migrant")
y<-do.call(paste, c(as.list(x), sep=" "))
k<-paste(y,";",sep="")
x <- c("female", "WITH", "age", "edu", "migrant")
cat(cat(x), ";", sep="")
x <- c("female", "WITH", "age", "edu", "migrant")
y<-do.call(paste, c(as.list(x), sep=" "))
k<-paste(y,";",sep="")
[1] "female WITH age edu migrant;"