从R中的1创建2个向量

时间:2018-07-17 05:14:16

标签: r design-patterns matching

我正在使用base R尝试将以下字符串拆分为2:

some_text | number1 (number2) | number1 (number2) | number1 (number2)

vec1 <- number1 number1 number1 

vec2 <- number2 number2 number2

我已经能够删除some_text|符号,但需要帮助,基于模式匹配来创建矢量。

2 个答案:

答案 0 :(得分:3)

这是使用strsplitsubapply的基本R选项:

x <- "some_text | 1 (2) | 3 (4) | 5 (6)"
y <- strsplit(x, "\\s*\\|\\s*", perl=TRUE)
number1 <- sapply(y, function(x) { sub(" \\(\\d+\\)", "", x) })[2:4]
number2 <- sapply(y, function(x) { sub("\\d+ \\((\\d+)\\)", "\\1", x) })[2:4]

number1
number2

[1] "1" "3" "5"
[1] "2" "4" "6"

Demo

答案 1 :(得分:1)

我们可以将base Rstrsplit一起使用

m1 <- lapply(strsplit(str1, "[ |()]"), function(x)
                  matrix(x[x!=""][-1], ncol=2, byrow= TRUE))[[1]]
vec1 <- m1[,1]
vec2 <- m1[,2] 
vec1
#[1] "number1" "number1" "number1"

vec2
#[1] "number2" "number2" "number2"

数据

str1 <- 'some_text | number1 (number2) | number1 (number2) | number1 (number2)'