【问题标题】:Remove whatever is after a character but exist the same character删除字符之后但存在相同字符的任何内容
【发布时间】:2018-10-05 10:37:21
【问题描述】:

在这样的数据框中:

df <- data.frame(id=c(1,2,3,4), text = c("word1","word2","word3","word4"), ts = c("something1,here,other","something2,here,other","something5,here,other","something4,here,other")

我想只保留 ts 列中第一个逗号之前存在的内容,并删除它之后的任何内容。像这样的结果:

df <- data.frame(id=c(1,2,3,4), text = c("word1","word2","word3","word4"), ts = c("something1","something2","something5","something4")

我试过了,但它不适合:

df$ts <- gsub(",","",df$ts)

我该怎么做?

【问题讨论】:

    标签: r


    【解决方案1】:

    你们很亲近... 使用,.* 作为模式,替换逗号第一个逗号之后的所有内容(即.*-部分)。

    df$ts <- gsub( ",.*", "", df$ts )
    
    #   id  text         ts
    # 1  1 word1 something1
    # 2  2 word2 something2
    # 3  3 word3 something5
    # 4  4 word4 something4            
    

    阅读更多关于正则表达式的信息:http://stat545.com/block022_regular-expression.html

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多