按名称引用列名

Referring to column names by name

我发现 this solution 给列前缀:

m2 <- cbind(1,1:4)
colnames(m2) <- c("x","Y")
colnames(m2) <- paste("Sub", colnames(m2), sep = "_")
m2

我想做的是,使用其列名仅粘贴前缀两列 x

我试过的其他几件事中:

colnames(m2)["x"] <- paste("Sub", colnames(m2)["x"], sep = "_")

最好的方法是什么?

期望的输出:

colnames(m2)[1] <- paste("Sub", colnames(m2)[1], sep = "_")

编辑

使用 Maël 的解决方案,我尝试执行以下操作:

m2 <- cbind(1,1:4,4:1)
colnames(m2) <- c("x","y","z")
colnames(m2)[colnames(m2) == c("x","z")] <- paste("Sub", colnames(m2)[colnames(m2) == c("x","z")], sep = "_")
m2 <- cbind(1,1:4)
colnames(m2) <- c("x","Y")

colnames(m2)[colnames(m2) == "x"] <- paste("Sub", colnames(m2)[colnames(m2) == "x"], sep = "_")

m2
#     Sub_x Y
#[1,]     1 1
#[2,]     1 2
#[3,]     1 3
#[4,]     1 4

有多个值,使用%in%:

m2 <- cbind(1,1:4,4:1)
colnames(m2) <- c("x","y","z")
colnames(m2)[colnames(m2) %in% c("x","z")] <- paste("Sub", colnames(m2)[colnames(m2) %in% c("x","z")], sep = "_")

     Sub_x y Sub_z
[1,]     1 1     4
[2,]     1 2     3
[3,]     1 3     2
[4,]     1 4     1