Reputation: 487
I have a dataset with a name column which has last name and first name. I need to swap them to have first name and last name. Here's my dataset:
df=data.frame(Id=c("10","50"), Name=c("NAGAR MAYANK","PETER MARK"), Street= c("Newark Ave","Grant Ave"),Country=c("NJ","TX"))
I have tried the below code to work:
sub("(\\w+),\\s(\\w+)","\\2\\1", dummy$Name)
However, this gives me the name as it is, i.e., "NAGAR MAYANK" and "PETER MARK".
I need the output as below:
| Id | Name | Street | State |
|----|---------------|------------|-------|
| 10 | MAYANK NAGAR | Newark Ave | NJ |
| 50 | MARK PETER | Grant Ave | TX |
Upvotes: 1
Views: 1036
Reputation: 28705
Your regex is almost correct, it just includes a comma which isn't present in the strings so the pattern isn't detected and no matching/replacement is done. (As noted by @Mosquite)
df$Name <- sub('(\\w) (\\w)', '\\2 \\1', df$Name)
df
# Id Name Street Country
# 1 10 MAYANK NAGAR Newark Ave NJ
# 2 50 MARK PETER Grant Ave TX
Upvotes: 4
Reputation: 5719
Another solution could be cSplit
:
library(splitstackshape)
df.tmp <- cSplit(df, "Name", " ")
df$Name <- paste(df.tmp$Name_2, df.tmp$Name_1, sep =" ")
> df
Id Name Street Country
1 10 MAYANK NAGAR Newark Ave NJ
2 50 MARK PETER Grant Ave TX
Upvotes: 3
Reputation: 40141
For this, you can use word()
from stringr
library:
df$Name <- with(df, paste(word(Name, 2), word(Name, 1)))
Id Name Street Country
1 10 MAYANK NAGAR Newark Ave NJ
2 50 MARK PETER Grant Ave TX
Upvotes: 5