【问题标题】:Create a new column is returning as list创建一个新列作为列表返回
【发布时间】:2021-11-30 19:02:01
【问题描述】:

我有一个数据框。我需要删除“href”,因此我使用的是 str_match_all。但删除“href”后,新列的类显示为列表。谁能帮帮我

asd <- data.frame(a = c("<a href=https://abc>Click Here</a>","sdsd","<a href=https://xvd>Click Here</a>"))
asd$ew <- str_match_all(asd$a, "http[s]{0,1}://[^ ]+")
asd
                                   a                ew
<a href=https://abc>Click Here</a>        https://abc>Click
                              sdsd                  
<a href=https://xvd>Click Here</a>        https://xvd>Click
class(asd$ew)
"list"

预期输出

class(asd$ew)
 "character"

【问题讨论】:

    标签: r regex dataframe stringr


    【解决方案1】:

    使用stringr::str_extract 而不是stringr::str_match_all

    asd$ew <- stringr::str_extract(asd$a, "http[s]{0,1}://[^ ]+")
    #asd$ew <- stringr::str_extract(asd$a, "https?://[^ ]+") #Alternative
    class(asd$ew)
    #[1] "character"
    
    asd
    #                                   a                ew
    #1 <a href=https://abc>Click Here</a> https://abc>Click
    #2                               sdsd              <NA>
    #3 <a href=https://xvd>Click Here</a> https://xvd>Click
    

    【讨论】:

      【解决方案2】:

      使用as.character:

      > asd$ew <- as.character(str_match_all(asd$a, "http[s]{0,1}://[^ ]+"))
      > class(asd$ew)
      [1] "character"
      > 
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2022-01-28
        • 1970-01-01
        • 2022-06-15
        • 1970-01-01
        • 2019-11-29
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多