【问题标题】:Is there a way in R to convert the following character variable?R中有没有办法转换以下字符变量?
【发布时间】:2021-01-04 22:06:54
【问题描述】:

我有以下数据框,其中包含一个表示高速公路上车道数的字符变量,我可以将这个向量替换为具有数字而不是字母的类似向量吗?

df<- structure(list(Blocked.Lanes = c("|RS|RS|ML|", "|RS|", "|RS|ML|ML|ML|ML|", 
"|RS|", "|RS|RE|", "|ML|ML|ML|", "|RS|ML|", "|RS|", "|ML|ML|ML|ML|ML|ML|", 
"|RS|ML|ML|"), Event.Id = c(240314L, 240381L, 240396L, 240796L, 
240948L, 241089L, 241190L, 241225L, 241226L, 241241L)), row.names = c(NA, 
10L), class = "data.frame")

输出应该类似于下面的 df2:

df2<- structure(list(Blocked.Lanes = c(3L, 1L, 5L, 1L, 2L, 3L, 2L, 
1L, 6L, 3L), Event.Id = c(240314L, 240381L, 240396L, 240796L, 
240948L, 241089L, 241190L, 241225L, 241226L, 241241L)), class = "data.frame", row.names = c(NA, 
-10L))

【问题讨论】:

    标签: r dplyr tidyverse data-manipulation data-cleaning


    【解决方案1】:

    一种方法是计算每个字符串中"|" 的数量。我们用- 1 减去它,因为还有一个"|"

    stringr::str_count(df$Blocked.Lanes, '\\|') - 1
    #[1] 3 1 5 1 2 3 2 1 6 3
    

    在基础 R 中:

    lengths(gregexpr("\\|", df$Blocked.Lanes)) - 1
    

    另一种方法是计算字符串中的确切单词。

    stringr::str_count(df$Blocked.Lanes, '\\w+')
    lengths(gregexpr("\\w+", df$Blocked.Lanes))
    

    【讨论】:

      【解决方案2】:

      与 Ronak 的解决方案类似,您也可以这样做:

       stringr:str_count(df$Blocked.Lanes, "\\b[A-Z]{2}\\b") 
      

      如果车道总是 2 个字母长,或者

       stringr:str_count(df$Blocked.Lanes, "\\b[A-Z]+\\b") 
      

      如果车道总是至少一个字母长。

       stringr:str_count(df$Blocked.Lanes, "(?<=\\|)[A-Z]+(?=\\|)")
      

      也可以。

      【讨论】:

        【解决方案3】:

        不像@Ronak Shah 那样简洁,而是 Base R 中的另一种方法。 在字符串文字 "|" 上拆分字符串,然后计算元素:

        df2 <- transform(df, Blocked.Lanes = lengths(Map(function(x) x[x != ""], 
                       strsplit(df$Blocked.Lanes, "|", fixed = TRUE))))
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2021-10-14
          • 1970-01-01
          • 1970-01-01
          • 2021-06-22
          • 2018-10-23
          • 2021-11-16
          • 1970-01-01
          相关资源
          最近更新 更多