簡體   English   中英

在R中首次出現特殊字符之前獲取所有字符

[英]Getting all characters ahead of first appearance of special character in R

我希望得到所有超過第一個“。”的角色。 如果有的話。 否則,我想找回相同的字符(“8” - >“8”)。

例:

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

我想得到這樣的東西:

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

我的想法是將每個元素拆分為“。” 然后只進行第一次拆分。 我找不到有效的解決方案......

你可以使用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+")

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")

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM