Hi
I have a list of names and would like to shorten every name in the column eg
I Have
David Smith
Chris Brown
etc
would like
D. Smith
C. Brown
etc
Any ideas
Hi
I have a list of names and would like to shorten every name in the column eg
I Have
David Smith
Chris Brown
etc
would like
D. Smith
C. Brown
etc
Any ideas
library(tidyverse)
(t1 <- tibble(n1 =c("David Smith","Chris Brown")))
(t2 <- mutate(rowwise(t1),
n2=str_split(n1," ",n=Inf),
n3=paste0(substr(n2[[1]],1,1),"."),
n4 =paste(n3,paste0(n2[-1]))) %>%
ungroup())
pull(t2,n4)
A somewhat shorter version, utilising regexp:
library(tidyverse)
t1 <- tibble(n1 =c("David Smith","Chris Brown"))
t2 <- t1 %>%
rowwise() %>%
mutate(n1 = str_replace(n1, "(^.).*( )", "\\1.\\2"))
t2
#> # A tibble: 2 × 1
#> # Rowwise:
#> n1
#> <chr>
#> 1 D. Smith
#> 2 C. Brown
Created on 2021-11-03 by the reprex package (v2.0.1)
Many, Many Thanks, spot on to all
Many thanks for your replies
How to adapt the code to do this on a entire df column, eg
df$Name
Cheers
This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.
If you have a query related to it or one of the replies, start a new topic and refer back with a link.