I found this solution to give columns prefixes:
m2 <- cbind(1,1:4)
colnames(m2) <- c("x","Y")
colnames(m2) <- paste("Sub", colnames(m2), sep = "_")
m2
What I would like to do instead, is paste the prefix only two column x
, by using its column name.
Among several other things I tried:
colnames(m2)["x"] <- paste("Sub", colnames(m2)["x"], sep = "_")
What would be the best way to do this?
Desired output:
colnames(m2)[1] <- paste("Sub", colnames(m2)[1], sep = "_")
EDIT
Using Maël's solution I tried to do the following:
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 = "_")
CodePudding user response:
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
with more than one value, use %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