我想使用 readr::read_fwf 從原始文本準備一個表格。有一個引數 col_position 負責確定在我的情況下可能不同的列寬度。表始終包含 4 列,并且基于字串中的 4 個第一個單詞,例如:
category variable description value sth
> text_for_column_width = "category variable description value sth"
> nchar("category ")
[1] 12
> nchar("variable ")
[1] 11
> nchar("description ")
[1] 17
> nchar("value ")
[1] 11
我想獲得 4 個第一個單詞,但要保留category 8[ab] 4[spaces] 個字符的空格,最后創建一個向量,包括四個名稱 c(12,11,17,11) 中每一個的字符數。我嘗試將 strsplit 與空間拆分引數一起使用,然后計算現有的零,但是我相信使用正確的正則運算式有更快的方法。
uj5u.com熱心網友回復:
一個可能的解決方案,使用stringr:
library(tidyverse)
text_for_column_width = "category variable description value sth"
strings <- text_for_column_width %>%
str_remove("sth$") %>%
str_split("(?<=\\s)(?=\\S)") %>%
unlist
strings
#> [1] "category " "variable " "description "
#> [4] "value "
strings %>% str_count
#> [1] 12 11 17 11
uj5u.com熱心網友回復:
您可以使用utils::strcapture:
text_for_column_width = "category variable description value sth"
pattern <- "^(\\S \\s )(\\S \\s )(\\S \\s )(\\S \\s*)"
result <- utils::strcapture(pattern, text_for_column_width, list(f1 = character(), f2 = character(), f3 = character(), f4 = character()))
nchar(as.character(as.vector(result[1,])))
## => [1] 12 11 17 11
請參閱正則運算式演示。^(\S \s )(\S \s )(\S \s )(\S \s*)比賽_
^- 字串的開始(\S \s )- 第 1 組:一個或多個非空白字符,然后是一個或多個空白(\S \s )- 第 2 組:一個或多個非空白字符,然后是一個或多個空格(\S \s )- 第 3 組:一個或多個非空白字符,然后是一個或多個空白(\S \s*)- 第 4 組:一個或多個非空白字符,然后是零個或多個空白
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/414691.html
標籤:
上一篇:在R中用ggplot2重疊許多圖
