[英]How to split strings and numbers in R?
我有以下形式的字符向量(這只是一個示例):
R1Ng(10)
test(0)
n.Ex1T(34)
如上所示,第一部分始終是字母數字和標點符號的組合,然后在括號內帶有數字。 我想創建一個數字向量,它將值存儲在括號內,並且每個數字都應具有name屬性,並且name屬性應該是數字之前的字符串。 因此,例如,我想存儲10
, 0
, 34
,數字矢量內部和它們的name屬性應該是, R1Ng
, test
, n.Ex1T
,分別。
我總是可以做這樣的事情來獲取數字並創建一個數值向量:
counts <- regmatches(data, gregexpr("[[:digit:]]+", data))
as.numeric(unlist(counts))
但是,如何提取第一個字符串部分,並將其存儲為該數字數組的name屬性?
這個怎么樣:
x <- c("R1Ng(10)", "test(0)", "n.Ex1T(34)")
data.frame(Name = gsub( "\\(.*", "", x),
Count = as.numeric(gsub(".*?\\((.*?)\\).*", "\\1", x)))
# Name Count
# 1 R1Ng 10
# 2 test 0
# 3 n.Ex1T 34
或作為矢量
setNames(as.numeric(gsub(".*?\\((.*?)\\).*", "\\1", x)),
gsub( "\\(.*", "", x ))
# R1Ng test n.Ex1T
# 10 0 34
這是使用相同表達式並捕獲括號的另一個變體:
temp <- c("R1Ng(10)", "test(0)", "n.Ex1T(34)")
data.frame(Name=gsub("^(.*)\\((\\d+)\\)$", "\\1", temp),
count=gsub("^(.*)\\((\\d+)\\)$", "\\2", temp))
我們可以使用str_extract_all
library(stringr)
lst <- str_extract_all(x, "[^()]+")
或從base R
strsplit
lst <- strsplit(x, "[()]")
如果我們需要存儲為命名vector
sapply(lst, function(x) setNames(as.numeric(x[2]), x[1]))
# R1Ng test n.Ex1T
# 10 0 34
x <- c("R1Ng(10)", "test(0)", "n.Ex1T(34)")
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.