Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I want to remove commas and every characters after commas in strings over all columns

from <- c("UK, port unspecified", "Nantes", "London", "America", "La Martinique, port unspecified")
to <- c("Benin", "Widha", "France, *", "America, Port unspecified", "London")

network <- data.frame(from, to)

My df :

                              from                        to
 1            UK, port unspecified                     Benin
 2                          Nantes                     Widha
 3                          London                 France, *
 4                         America America, Port unspecified
 5 La Martinique, port unspecified                    London

What I want :

                              from                        to
 1                               UK                    Benin
 2                          Nantes                     Widha
 3                          London                    France
 4                         America                   America
 5                    La Martinique                    London

Can I combine transmute_all (or transmute_if) (package dplyr) and split (package tidyr) functions in dplyr pipe ?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
234 views
Welcome To Ask or Share your Answers For Others

1 Answer

You can use mutate_all/transmute_all and remove everything after comma using sub.

library(dplyr)
network  %>%  mutate_all(~sub(",.*", "", .))

#           from      to
#1            UK   Benin
#2        Nantes   Widha
#3        London  France
#4       America America
#5 La Martinique  London

Or in base R with lapply.

df[] <- lapply(network, function(x) sub(",.*", "", x))

data

Reading data as characters by using stringsAsFactors = FALSE.

network <- data.frame(from, to, stringsAsFactors = FALSE)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...