在r studio中使用rep命令重命名特定的列

时间:2016-10-26 14:27:07

标签: r

我试图通过重命名将黑猩猩和人类大脑样本组合在一起。总共有24个样本,前12个是黑猩猩,最后是人类。它通过脑区重复3次(3个不同的黑猩猩/ 4个不同脑区的人类样本)。我已经能够生成所有24个样本名称,但它们的顺序不正确。它应该是CHPrefrontal,CHCaudate,CHCerebellum,CHBroca然后重复那些2次,然后相同的设置为人类样品。有什么建议?这就是我到目前为止所做的:

trts=paste(rep(c("CHPrefrontal","CHCaudate","CHCerebellum","CHBroca","HUPre    frontal","HUCaudate","HUCerebellum","HUBroca"),each=3),rep(c(1:3, 1:3,        times=3)),sep="")
paste(trts)

输出结果为:

[1] "CHPrefrontal1" "CHPrefrontal2" "CHPrefrontal3"
[4] "CHCaudate1"    "CHCaudate2"    "CHCaudate3"   
[7] "CHCerebellum3" "CHCerebellum1" "CHCerebellum2"
[10] "CHBroca3"      "CHBroca1"      "CHBroca2"     
[13] "HUPrefrontal3" "HUPrefrontal3" "HUPrefrontal1"
[16] "HUCaudate2"    "HUCaudate3"    "HUCaudate1"   
[19] "HUCerebellum2" "HUCerebellum3" "HUCerebellum3"
[22] "HUBroca1"      "HUBroca2"      "HUBroca3"

3 个答案:

答案 0 :(得分:0)

来自:Extracting the last n characters from a string in R

我们有这个功能:

substrRight <- function(x, n){ substr(x, nchar(x)-n+1, nchar(x)) }

我们可以用它来提取最后一个数字。然后我们使用它来计算顺序,最后使用这个顺序重新排序向量:

trts[order(as.numeric(substrRight(trts,1)))]

输出:

[1] "CHPrefrontal1" "CHCaudate1"
[3] "CHCerebellum1" "CHBroca1"
[5] "HUPre frontal1" "HUCaudate1"
[7] "HUBroca1" "CHPrefrontal2"
[9] "CHCaudate2" "CHCerebellum2"
[11] "CHBroca2" "HUCaudate2"
[13] "HUCerebellum2" "HUBroca2"
[15] "CHPrefrontal3" "CHCaudate3"
[17] "CHCerebellum3" "CHBroca3"
[19] "HUPre frontal3" "HUPre frontal3" [21] "HUCaudate3" "HUCerebellum3"
[23] "HUCerebellum3" "HUBroca3"

答案 1 :(得分:0)

如果您不想附上数字,请尝试:

rep(paste0(rep(c("CH", "HU"), each=3), c("Prefrontal", "Caudate", "Cerebellum", "Broca")), 3)
# [1] "CHPrefrontal" "CHCaudate"    "CHCerebellum" "HUBroca"      "HUPrefrontal"
# [6] "HUCaudate"    "CHPrefrontal" "CHCaudate"    "CHCerebellum" "HUBroca"     
# [11] "HUPrefrontal" "HUCaudate"    "CHPrefrontal" "CHCaudate"    "CHCerebellum"
# [16] "HUBroca"      "HUPrefrontal" "HUCaudate"  

答案 2 :(得分:0)

你可以这样做:

paste0(rep(c("CH", "HU"), each = 12), rep(c("Prefrontal", "Caudate", "Cerebellum", "Broca"), 4))

# [1] "CHPrefrontal" "CHCaudate"    "CHCerebellum" "CHBroca"      "CHPrefrontal" "CHCaudate"   
# [7] "CHCerebellum" "CHBroca"      "CHPrefrontal" "CHCaudate"    "CHCerebellum" "CHBroca"     
# [13] "HUPrefrontal" "HUCaudate"    "HUCerebellum" "HUBroca"      "HUPrefrontal" "HUCaudate"   
# [19] "HUCerebellum" "HUBroca"      "HUPrefrontal" "HUCaudate"    "HUCerebellum" "HUBroca"