我有一个数据集$Plaza
,行名称为-
"Main Plaza 1"
"Main Plaza 2"
"Main Plaza 3"
"Main Plaza 1"
"Main Plaza 5"
我必须将第二次出现的
'Main Plaza 1'
重命名为'Main Plaza 1_second'
。我尝试了以下代码-
library("dplyr")
d <- grep("Main Plaza 1", dataset$Plaza)
for(i in length(d))
{
ifelse(length(d) == 2,
str_replace(dataset$Plaza, grep("^Main Lane Plaza 1"),
"Main Lane Plaza 1(second)"), NA)
break()
}
我已经尝试了几次,没有更多的代码,找不到解决方案。请帮忙!
最佳答案
为了向出现多次的每个字符串添加_second
,可以使用:
plaza <- c("Main Plaza 1", "Main Plaza 2", "Main Plaza 3", "Main Plaza 1", "Main Plaza 5")
dups <- duplicated(plaza)
plaza[dups] <- paste0(plaza[dups], "_second")
plaza
## [1] "Main Plaza 1" "Main Plaza 2" "Main Plaza 3" "Main Plaza 1_second" "Main Plaza 5"
为了仅修改“ Main Plaza 1”的第二次出现(但不更改任何其他重复的元素),请使用:
plaza <- c("Main Plaza 1", "Main Plaza 2", "Main Plaza 3", "Main Plaza 1", "Main Plaza 5")
i <- which(plaza == "Main Plaza 1")[2]
plaza[i] <- paste0(plaza[i], "_second")
plaza
## [1] "Main Plaza 1" "Main Plaza 2" "Main Plaza 3" "Main Plaza 1_second" "Main Plaza 5"