我有一个像这样的矩阵:
mat
[,1] [,2] [,3] [,4] [,5]
1271 "04" "7" "-01" "08" "W"
现在我想使用这些信息:
paste0("path","nhg","_",mat[1], "_", mat[2], "_", mat[3] , "_", mat[5] ))
但是对于这种情况(我不知道我有多少行):
mat <- matrix(c("21", "343", "86", "0486", "W2",
"21", "33", "16", "02", "n9",
"11", "343", "16", "693", "n07"), byrow=TRUE, ncol=5)
mat
# [,1] [,2] [,3] [,4] [,5]
# [1,] "21" "343" "86" "0486" "W2"
# [2,] "21" "33" "16" "02" "n9"
# [3,] "11" "343" "16" "693" "n07"
所以我想重复一遍:每行paste0("path","nhg","_",mat[1], "_", mat[2], "_", mat[3] , "_", mat[5] ))
。
答案 0 :(得分:2)
如果我已正确理解您的请求,这应该有效:
mat <- matrix(c("21", "343", "86", "0486", "W2",
"21", "33", "16", "02", "n9",
"11", "343", "16", "693", "n07"), byrow=TRUE, ncol=5)
f <- function(vec) {paste0("path","nhg_", paste0(vec, collapse="_"))}
apply(mat, 1, f)
# [1] "pathnhg_21_343_86_0486_W2" "pathnhg_21_33_16_02_n9" "pathnhg_11_343_16_693_n07"
答案 1 :(得分:1)
怎么样:
apply(mat, 1, function(x){paste0("path","nhg","_",x[1], "_", x[2], "_", x[3] , "_", x[5] )})
编辑:有点太晚了我猜:)