[英]Rename a lot of column r
I have 2 data frames with column names: 我有2个具有列名称的数据框:
print(colnames(selectedTrainData))
[1] "V331" "V305" "V310" "V161" "V322" "V271" "V355" "V83" "V185" "V10"
print(colnames(selectedTestData))
[1] "V330" "V304" "V309" "V160" "V321" "V270" "V354" "V82" "V184" "V9"
Here is difference at 1 between colnames. 这是两个姓之间的差异。 How rename colnames of 1st data frame, to make it less at 1?
如何重命名第一个数据框的同名,以使其小于1?
Here is a step-by-step breakdown 这是分步细分
## first grab the column names as its own object
nms <- colnames(selectedTestData)
## second, strip out the starting "V"
nms <- gsub("V", "", nms)
## next, convert to a number
nms <- as.numeric(nms)
## substract 1 from each number
nms <- nms - 1
## The numbers are ready, now just paste the "V" back
nms <- paste("V", nms, sep="")
## Lastly, put the names back onto the original matrix or data.frame
colnames(selectedTestData) <- nms
Starting:
[1] "V330" "V304" "V309" "V160" "V321" "V270" "V354" "V82" "V184" "V9"
Ending:
[1] "V329" "V303" "V308" "V159" "V320" "V269" "V353" "V81" "V183" "V8"
If the numbers are always trailing elements, this works: 如果数字始终是尾随元素,则可以这样做:
txt <- colnames(selectedTrainData)
r <- regexpr('\\d+', txt)
colnames(selectedTrainData) <-
paste(
substr(txt, 1, r-1),
as.numeric(substring(txt, r))-1,
sep=''
)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.