【问题标题】:Getting all characters ahead of first appearance of special character in R在 R 中首次出现特殊字符之前获取所有字符
【发布时间】:2015-12-20 17:09:53
【问题描述】:

我想获取第一个“。”之前的所有字符。如果有的话。否则,我想取回相同的字符(“8”->“8”)。

例子:

v<-c("7.7.4","8","12.6","11.5.2.1")

我想得到这样的东西:

[1] "7 "8" "12" "11"

我的想法是在“。”处分割每个元素。然后只取第一个拆分。我没有找到有效的解决方案...

【问题讨论】:

  • @rawr 为什么不只是numeric_version(v)[,1]
  • @Jota 因为我试图找出隐藏列表和 numeric_version(v)[[1]]numeric_version(v)[[1]][[1]]numeric_version(v)[[1]][[1]][[1]][[1]][[1]] 并且在兔子洞里走得太远了
  • @rawr 你应该继续发布它作为答案。我从来没有见过这个函数,对于给出的例子来说它非常好。
  • 应该是unlist(numeric_version(v)[,1])

标签: r string split


【解决方案1】:

您可以使用sub

sub("\\..*", "", v)
#[1] "7"  "8"  "12" "11"

或几个stringi 选项:

library(stringi)
stri_replace_first_regex(v, "\\..*", "")
#[1] "7"  "8"  "12" "11"
# extract vs. replace
stri_extract_first_regex(v, "[^\\.]+")
#[1] "7"  "8"  "12" "11"

如果您想使用拆分方法,这些方法将起作用:

unlist(strsplit(v, "\\..*"))
#[1] "7"  "8"  "12" "11"

# stringi option
unlist(stri_split_regex(v, "\\..*", omit_empty=TRUE))
#[1] "7"  "8"  "12" "11"
unlist(stri_split_fixed(v, ".", n=1, tokens_only=TRUE))
unlist(stri_split_regex(v, "[^\\w]", n=1, tokens_only=TRUE))

其他使用捕获组专门针对前导字符的sub 变体:

sub("(\\w+).+", "\\1", v) # \w matches [[:alnum:]_] (i.e. alphanumerics and underscores)
sub("([[:alnum:]]+).+", "\\1", v) # exclude underscores

# variations on a theme
sub("(\\w+)\\..*", "\\1", v)
sub("(\\d+)\\..*", "\\1", v) # narrower: \d for digits specifically
sub("(.+)\\..*", "\\1", v) # broader: "." matches any single character

# stringi variation just for fun:
stri_extract_first_regex(v, "\\w+")

【讨论】:

    【解决方案2】:

    scan() 实际上可以很好地解决这个问题。由于我们想要第一个 . 之前的所有内容,我们可以将其用作注释字符,scan() 将删除 v 中每个元素的所有内容,包括该字符之后的所有内容。

    scan(text = v, comment.char = ".")
    # [1]  7  8 12 11
    

    上面返回一个数字向量,这可能是你要去的地方。如果您需要坚持使用字符,请添加 what 参数以表示我们希望返回字符向量。

    scan(text = v, comment.char = ".", what = "")
    # [1] "7"  "8"  "12" "11"
    

    数据:

    v <- c("7.7.4", "8", "12.6", "11.5.2.1")
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-05-07
      • 2019-06-16
      • 2016-02-22
      • 2013-06-28
      • 1970-01-01
      • 2016-02-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多