我有一个名为 VEC 的字符串向量(> 100K元素),我想从中提取数据以形成数据帧;样本元素如下:
VEC[1]
"today's performance: SW= 33.9; west =13.85 East=70.09 and the north central =125.823, S.S. = 41.5"
VEC[2]
"sent as received South= 28.76 while the West =44.55, SouthEast=64.32; north-east =130; south west = 38.86"
...
我希望输出为:
列名不必像我指定的那样,但为了正确定义变量,应该是同类的。
我用下面的数字来匹配数字;我需要帮助才能使用适当的标题将它们映射到右侧列。
m <- gregexpr("[[:digit:]]+\\.*[[:digit:]]*", VEC, perl=TRUE)
regmatches(VEC, m)
答案 0 :(得分:1)
你知道所有的替代拼写,例如SW对西南吗?对我来说,这似乎非常重要,因为位置不合适。如果是这样,也许你可以这样做:
pat <- "SW|south west" #alternate spellings
i <- regmatches(VEC,regexec(pat,VEC)) # find them per string
i[lengths(i) == 0] <- NA_character_ # convert zeros to nas
i <- unlist(i)
f <- function(x) gsub(paste0(".*?(?<=",i[x],")\\D+(\\d+\\.?\\d*).*"),"\\1",VEC[x],perl = T) # some regex function to extract numbers after string occurence
SW <- sapply(seq_along(VEC),f) # extract
> SW
[1] "33.9" "38.86"
对每列重复
可能需要调整函数以适应nas,也许需要包含在ifelse()