简体   繁体   中英

How to fetch the second occurrence of a string in a column and rename it using R?

I have a dataset $Plaza with row names as -

"Main Plaza 1"

"Main Plaza 2"

"Main Plaza 3"

"Main Plaza 1"

"Main Plaza 5"

I have to rename the second occurrence of 'Main Plaza 1' to 'Main Plaza 1_second' .

I have tried the following code-

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()

}

I have tried multiple times with few more codes could not find the solution. Please help!

In order to add _second to every string that appears more than once, you can use:

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"

In order to modify only the second occurence of "Main Plaza 1" (but leave any other repeated elements untouched), use:

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"

You could simply subset the dataframe for the rows with your desired value, then index the second occurrence, like so:

pizza = data.frame(Name = c("Main Plaza 1",
    "Main Plaza 2",
    "Main Plaza 3",
    "Main Plaza 1",
    "Main Plaza 5"),
    stringsAsFactors = FALSE)

pizza[which(pizza$Name == "Main Plaza 1"),][2] <- "Main Lane Plaza 1(second)"

pizza

Result:

                       Name
1              Main Plaza 1
2              Main Plaza 2
3              Main Plaza 3
4 Main Lane Plaza 1(second)
5              Main Plaza 5

I would definitely try to start getting used to subsetting over looping in R, almost always.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM