【问题标题】:transmute over all columns : removing comma and every characters after comma转换所有列:删除逗号和逗号后的每个字符
【发布时间】:2020-02-26 09:14:36
【问题描述】:

我想删除所有列中字符串中逗号和逗号后的每个字符

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)

我的 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

我想要什么:

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

我可以在 dplyr 管道中组合transmute_all(或transmute_if)(dplyr 包)和split(tidyr 包)函数吗?

【问题讨论】:

    标签: r dplyr tidyr


    【解决方案1】:

    您可以使用mutate_all/transmute_all 并使用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
    

    或者在基础 R 中使用lapply

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

    数据

    使用stringsAsFactors = FALSE 将数据读取为字符。

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

    【讨论】:

    • 为什么不使用 transmute_all ?
    • @Wilcar 在这种情况下,您可以同时使用mutate_alltransmute_all
    • sub 是一个 grep 函数?所以我也可以你 str_extract 吗?
    • subgrep 是不同的功能。是的,您也可以使用str_extract,但是我认为使用sub 对我来说似乎很简单。也许str_removenetwork %&gt;% transmute_all(~str_remove(., ",.*"))
    猜你喜欢
    • 2012-12-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-10
    相关资源
    最近更新 更多