我正在使用R打印MPLUS命令。我必须指定许多变量之间的协方差。因此,我必须创建集合的所有子集。在 MPLUS 中,必须像这样指定它(如果我们考虑 4 个变量的列表 女性、年龄、教育移民(:
female WITH age edu migrant;
age WITH edu migrant;
edu WITH migrant;
它代表 4 个变量集合中大小 2 的所有子集(
女性与年龄;女性与教育;女性与移民;年龄与教育;年龄与移民;教育与移民;(。为了获得可以直接复制到 MPLUS 中的输出,我使用命令 cat((。不幸的是,我无法获得上面显示的输出,而只能获得此输出(注意分号(:
female WITH age edu migrant ;
age WITH edu migrant ;
edu WITH migrant ;
我玩了很多糊状物,猫和印刷品。但是要么我得到一个输出,在行尾的分号之前有一个空格(就像上面一样(,要么我得到这个:
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)
我希望我能足够仔细地列出问题(这完全是关于 R 字符串操作的(,并提前非常感谢您。
本
以下代码适合您吗?
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="")
现在字符串 k 将作为您想要的字符串 -
[1] "female WITH age edu migrant;"