我正在使用base R尝试将以下字符串拆分为2:
some_text | number1 (number2) | number1 (number2) | number1 (number2)
vec1 <- number1 number1 number1
vec2 <- number2 number2 number2
我已经能够删除some_text
和|
符号,但需要帮助,基于模式匹配来创建矢量。
答案 0 :(得分:3)
这是使用strsplit
,sub
和apply
的基本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"
答案 1 :(得分:1)
我们可以将base R
与strsplit
一起使用
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)'