给出一个示例:
my_string< - " 2a 5b-2c 2d = 9; 3a-2b 1c-3d = 34; -3a 3b 3b 2c 2c 4d = 33; 2a 3b 3b 4c 4c 4c 5d = 125"
s <- my_string
p <- ";"
s2 <- gsub(p,"",s)
w <- nchar(s) - nchar(s2) + 1
s1 <- my_string
p1 <- "[:a-z:]"
s3 <- gsub(p1,"",s1)
k <- (nchar(s1) - nchar(s3) )/w +1
my_string<-strsplit(my_string, ";")
my_string<-unlist(my_string)
my_string<-trimws(my_string)
for (i in 1:w) {
print(noquote(paste0(my_string[i])))
}
sp2 <- strsplit(my_string, "=")
b <- as.numeric(sapply(sp2, '[[', 2))
sp3 <- lapply(lapply(sp2, '[[', 1), function(s) gsub("([-+])([[:alpha:]])",
"\11\2", s))
sp3 <- lapply(sp3, trimws)
sp3 <- lapply(sp3, function(s1) sub("^([[:alpha:]])", "1\1", s1))
A <- do.call(rbind, lapply(sp3, function(x) as.numeric(unlist(strsplit(x,"
[[:alpha:]]")))))
x <- cbind(A,b)
x
此程序的输出是此矩阵:
b
[1,] 2 5 -2 2 9
[2,] 3 -2 1 -3 34
[3,] -3 3 2 4 33
[4,] 2 3 4 5 125
它的工作正确。但是,当至少一个方程式中不会发生某些方程中存在的变量时,问题就会出现。在这种情况下,该程序将不起作用。我的问题是:如何修改该方程系统:
my_string&lt; - " 2a 5b-2c = 9; 3a-2b-3d = 34; -3a 3b 3b 2c 4d = 33; 2a 4c 4c 4c 5d = 125"
将给出此输出:
b
[1,] 2 5 -2 0 9
[2,] 3 -2 0 -3 34
[3,] -3 3 2 4 33
[4,] 2 0 4 5 125
(每个列代表下一个变量,如果在任何方程式中不发生一些变量,则应返回特定位置的值0(
预先感谢您。
tidyverse
的一个选项将为
library(tidyverse)
str_split(my_string, "; ") %>%
magrittr::extract2(1) %>%
map_df(~ .x %>%
{
x1 <- str_extract_all(., pattern = "[0-9-]+")[[1]]
x2 <- c(str_extract_all(., pattern = "[a-z]+")[[1]], "e")
set_names(as.list(x1), x2)
}
%>%
as_tibble) %>%
select(a, b, c, d, e) %>%
mutate_all(funs(as.numeric(replace(., is.na(.), 0))))
# A tibble: 4 x 5
# a b c d e
# <dbl> <dbl> <dbl> <dbl> <dbl>
#1 2.00 5.00 -2.00 0 9.00
#2 3.00 -2.00 0 -3.00 34.0
#3 -3.00 3.00 2.00 4.00 33.0
#4 2.00 0 4.00 5.00 125