user3922483
user3922483

Reputation: 183

R - remove anything after comma from column

I'd like to strip this column so that it just shows last name - if there is a comma I'd like to remove the comma and anything after it. I have data column that is a mix of just last names and last, first. The data looks as follows:

Last Name  
Sample, A  
Tester  
Wilfred, Nancy  
Day, Bobby Jean  
Morris  

Upvotes: 10

Views: 28734

Answers (5)

acylam
acylam

Reputation: 18681

Also try strsplit:

string <- c("Sample, A", "Tester", "Wifred, Nancy", "Day, Bobby Jean", "Morris")

sapply(strsplit(string, ","), "[", 1)
#[1] "Sample" "Tester" "Wifred" "Day"    "Morris"

Upvotes: 0

user3619015
user3619015

Reputation: 176

This is will work

a <- read.delim("C:\\Desktop\\a.csv", row.names = NULL,header=TRUE, 
                 stringsAsFactors=FALSE,sep=",")
a=as.matrix(a)
Data=str_replace_all(string=a,pattern="\\,.*$",replacement=" ")

Upvotes: 0

akrun
akrun

Reputation: 887193

 str1 <- c("Sample, A", "Tester", "Wifred, Nancy", "Day, Bobby Jean", "Morris")
 library(stringr)
  str_extract(str1, perl('[A-Za-z]+(?=(,|\\b))'))
 #[1] "Sample" "Tester" "Wifred" "Day"   "Morris"  

Match alphabets [A-Za-z]+ and extract those which are followed by , or word boundary.

Upvotes: 0

martin
martin

Reputation: 3239

You can use gsub:

gsub(",.*", "", c("last only", "last, first"))
# [1] "last only" "last"

",.*" says: replace comma (,) and every character after that (.*), with nothing "".

Upvotes: 16

EDi
EDi

Reputation: 13280

You could use gsub() and some regex:

> x <- 'Day, Bobby Jean'
> gsub("(.*),.*", "\\1", x)
[1] "Day"

Upvotes: 22

Related Questions