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
You can use gsub:
gsub(",.*", "", c("last only", "last, first"))
# [1] "last only" "last"
",.*"
says: replace comma (,) and every character after that (.*), with nothing ""
.
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.
You could use gsub() and some regex:
> x <- 'Day, Bobby Jean'
> gsub("(.*),.*", "\\1", x)
[1] "Day"
Also try strsplit
:
string <- c("Sample, A", "Tester", "Wifred, Nancy", "Day, Bobby Jean", "Morris")
sapply(strsplit(string, ","), "[", 1)
#[1] "Sample" "Tester" "Wifred" "Day" "Morris"
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=" ")