我有一个矢量
Names<-c("A", "B", "C")
我最终会喜欢这样的事情
c("A_Mean", "A_Median", "A_InGroupVar", "B_Mean", "B_Median", "B_InGroupVar", "C_Mean", "C_Median", "C_InGroupVar")
我尝试过粘贴功能
c(paste(Names, "_Mean"), paste(Names, "_Median"), paste(Names, "_InGroupvar"))
但我需要按名称排序矢量。我知道我可以在循环中轻松完成这项工作,但我正在寻找更优雅的解决方案。
答案 0 :(得分:3)
这是一种原始方法:
Names <- rep(c("A", "B", "C"), each=3)
Stats <- rep(c("Mean", "Median", "InGroupVar"), 3)
paste(Names, Stats, sep="_")
[1] "A_Mean" "A_Median" "A_InGroupVar" "B_Mean" "B_Median"
[6] "B_InGroupVar" "C_Mean" "C_Median" "C_InGroupVar"
答案 1 :(得分:3)
我更喜欢sprintf
这个特殊问题:
Names <- c("A", "B", "C")
sprintf("%s_%s",
rep(Names, each = 3),
c("Mean", "Median", "InGroupVar"))
# [1] "A_Mean" "A_Median" "A_InGroupVar" "B_Mean"
# [5] "B_Median" "B_InGroupVar" "C_Mean" "C_Median"
# [9] "C_InGroupVar"
或者,这也有效,但会以不同的顺序给出结果:
do.call(paste,
c(expand.grid(
Names, c("Mean", "Median", "InGroupVar")),
sep = "_"))
# [1] "A_Mean" "B_Mean" "C_Mean" "A_Median"
# [5] "B_Median" "C_Median" "A_InGroupVar" "B_InGroupVar"
# [9] "C_InGroupVar"