向字符串添加唯一数字
我希望将一个数字附加到一个字符向量上,这样每一行都会收到一个与前一行不同的唯一数字,尽管相对于前一行是 +1。这样的n+1。
我试过了:
test.all$ly_name <- sub("^", 1:nrow(test.all$ly_name), test.all$ly_name )
它的样子:
1Prairie_Potholes
1Prairie_Potholes
1Prairie_Potholes
.
.
.
预期的:
Prairie_Potholes1
Prairie_Potholes2
Prairie_Potholes3
.
.
.
但是,这仅分配第一个数字 1。
可重现的代码:
c("Prairie_Potholes", "Prairie_Potholes", "Prairie_Potholes",
"Prairie_Potholes", "Prairie_Potholes", "Prairie_Potholes", "Prairie_Potholes",
"Prairie_Potholes", "Prairie_Potholes", "Boreal_Hardwood_Transition",
"Boreal_Hardwood_Transition", "Boreal_Hardwood_Transition", "Boreal_Hardwood_Transition",
"Boreal_Hardwood_Transition", "Boreal_Hardwood_Transition")
回答
重复中唯一
make.unique(c("Prairie_Potholes", "Prairie_Potholes", "Prairie_Potholes",
"Prairie_Potholes", "Prairie_Potholes", "Prairie_Potholes", "Prairie_Potholes",
"Prairie_Potholes", "Prairie_Potholes", "Boreal_Hardwood_Transition",
"Boreal_Hardwood_Transition", "Boreal_Hardwood_Transition", "Boreal_Hardwood_Transition",
"Boreal_Hardwood_Transition", "Boreal_Hardwood_Transition"), sep = "")
[1] "Prairie_Potholes" "Prairie_Potholes1" "Prairie_Potholes2" "Prairie_Potholes3" "Prairie_Potholes4"
[6] "Prairie_Potholes5" "Prairie_Potholes6" "Prairie_Potholes7" "Prairie_Potholes8" "Boreal_Hardwood_Transition"
[11] "Boreal_Hardwood_Transition1" "Boreal_Hardwood_Transition2" "Boreal_Hardwood_Transition3" "Boreal_Hardwood_Transition4" "Boreal_Hardwood_Transition5"
给每一行添加一个后缀
x <- c("Prairie_Potholes", "Prairie_Potholes", "Prairie_Potholes",
"Prairie_Potholes", "Prairie_Potholes", "Prairie_Potholes", "Prairie_Potholes",
"Prairie_Potholes", "Prairie_Potholes", "Boreal_Hardwood_Transition",
"Boreal_Hardwood_Transition", "Boreal_Hardwood_Transition", "Boreal_Hardwood_Transition",
"Boreal_Hardwood_Transition", "Boreal_Hardwood_Transition")
x <- paste0(x, 1:length(x))
x
[1] "Prairie_Potholes1" "Prairie_Potholes2" "Prairie_Potholes3" "Prairie_Potholes4" "Prairie_Potholes5"
[6] "Prairie_Potholes6" "Prairie_Potholes7" "Prairie_Potholes8" "Prairie_Potholes9" "Boreal_Hardwood_Transition10"
[11] "Boreal_Hardwood_Transition11" "Boreal_Hardwood_Transition12" "Boreal_Hardwood_Transition13" "Boreal_Hardwood_Transition14" "Boreal_Hardwood_Transition15"