【问题标题】:Gsub apostrophe in data frame R数据帧 R 中的 Gsub 撇号
【发布时间】:2014-07-04 14:04:42
【问题描述】:

我需要从我的数据框中删除所有撇号,但只要我使用....

textDataL <- gsub("'","",textDataL)

当我只想从可能存在的任何文本中删除任何撇号时,数据框被破坏并且新数据框仅包含值和 NA?我是否遗漏了一些明显的撇号和数据框?

【问题讨论】:

    标签: r dataframe gsub apostrophe


    【解决方案1】:

    保持结构完整:

     dat1 <- data.frame(Col1= c("a woman's hat", "the boss's wife", "Mrs. Chang's house", "Mr Cool"),
     Col2= c("the class's hours", "Mr. Jones' golf clubs", "the canvas's size", "Texas' weather"),
     stringsAsFactors=F)
    

    我会用

         dat1[] <- lapply(dat1, gsub, pattern="'", replacement="")
    

         library(stringr)
         dat1[] <- lapply(dat1, str_replace_all, "'","")
     dat1
    #                Col1                 Col2
    # 1      a womans hat     the classs hours
    # 2    the bosss wife Mr. Jones golf clubs
    # 3 Mrs. Changs house     the canvass size
    # 4           Mr Cool        Texas weather
    

    【讨论】:

      【解决方案2】:

      您不想将gsub 直接应用于数据框,而是按列应用,例如

      apply(textDataL, 2, gsub, pattern = "'", replacement = "")
      

      【讨论】:

      • 我会假设结果是矩阵。如果是这种情况, gsub("'", "", as.matrix(textDataL) 应该可以工作。
      猜你喜欢
      • 2011-09-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-12-10
      • 1970-01-01
      • 1970-01-01
      • 2018-05-06
      • 2019-06-27
      相关资源
      最近更新 更多