Weiting Chen
Weiting Chen

Reputation: 213

How to get the text after the last comma?

I have a text, say:

s <- "Chengdu Shi, Sichuan Sheng, China"

I want to use a function such that I will only get the words after the last comma(i.e. China).

I have tried several methods like grep but they return all the instances instead of the last.

Upvotes: 0

Views: 2364

Answers (5)

Big_J
Big_J

Reputation: 1

# Define the string
s <- "Chengdu Shi, Sichuan Sheng, China"

# Split the string by commas
split_string <- strsplit(s, ",")[[1]]

# Trim whitespace and get the last element
last_element <- trimws(split_string[length(split_string)])

# Print the result
print(last_element)

Upvotes: 0

Raja Saha
Raja Saha

Reputation: 509

Try:

wordAfterLastComma <- function(x, sep = ","){
  x <- sapply(strsplit(x, sep),"[")
  trimws(x[[length(x)]])
}

s1 <- "Chengdu Shi, Sichuan Sheng, China"
s2 <- "Chengdu Shi, Sichuan Sheng, China,Chengdu Shi"

wordAfterLastComma(s1)
# [1] "China"

wordAfterLastComma(s2)
# [1] "Chengdu Shi"

Upvotes: 1

Arun kumar mahesh
Arun kumar mahesh

Reputation: 2359

Use stringi package

   s <- "Chengdu Shi, Sichuan Sheng, China"

    library(stringi)

    stri_extract_last_words(s)
    [1] "China"

Upvotes: 0

NelsonGon
NelsonGon

Reputation: 13319

Try:

sapply(strsplit(s,", "),"[")[3]
[1] "China"

Upvotes: 0

Saurabh Chauhan
Saurabh Chauhan

Reputation: 3221

Using sub:

# Simply get the text after last comma ,
sub('.*\\,', '', s)

OR

Using word from library(stringr) package:

s <- "Chengdu Shi, Sichuan Sheng, China"
word(s,3,sep=",") # Extract word from the last column

OR

# If your data is stored in data.frame
word(s,ncol(s),sep=",") # Extract last column data using column index

Output:

[1] " China"

Upvotes: 2

Related Questions