gpt4 book ai didi

r - 将唯一数字添加到字符串

转载 作者:行者123 更新时间:2023-12-05 08:48:00 25 4
gpt4 key购买 nike

我希望将一个数字附加到一个字符向量上,这样每一行都会收到一个与前一行不同的唯一数字,尽管相对于前一行是 +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"

关于r - 将唯一数字添加到字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66691315/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com