将文本文件输出分成两个向量

时间:2018-04-26 07:44:25

标签: r

所以我有输出

"[(9.010658025741577, 2.8047988414764404), (9.242822885513306, 2.66866397857666), (9.263759851455688, 2.6707050800323486), (9.515105962753296, 2.5500648021698)]"

我使用命令:

read_txt_file <- scan("my_file.txt", what="", sep="\n") 

现在我想将输出分成两个向量,因此它将是:

x = "[9.010658025741577, 9.242822885513306, 9.263759851455688, 9.515105962753296]" 

y= "[ 2.8047988414764404, 2.66866397857666, 2.6707050800323486), 2.5500648021698)]"

任何想法如何轻松地做到这一点?谢谢。

3 个答案:

答案 0 :(得分:2)

你可以试试这个:

text1 <- "[(9.010658025741577, 2.8047988414764404), (9.242822885513306, 2.66866397857666), (9.263759851455688, 2.6707050800323486), (9.515105962753296, 2.5500648021698)]"


x <- paste0("[",paste0(c(unlist(strsplit(gsub("[^0-9\\.\\,]", "", text1), ",")))[seq(1,7,2)], collapse = ", "), "]")
y <- paste0("[",paste0(c(unlist(strsplit(gsub("[^0-9\\.\\,]", "", text1), ",")))[seq(2,8,2)], collapse = ", "), "]")


> x
[1] "[9.010658025741577, 9.242822885513306, 9.263759851455688, 9.515105962753296]"
> y
[1] "[2.8047988414764404, 2.66866397857666, 2.6707050800323486, 2.5500648021698]"

使用gsub命令,您只保留数字,小数点和逗号。随后,将字符串拆分为子字符串,并使用逗号作为分隔符。然后你取消列出这些子串并将它们放在一个向量中。对于x,您保留不均匀元素,对于偶数元素。接下来,通过在paste0命令中设置collapse =“,”,将x(以及y)中的所有元素粘贴在一起。最后,在开头粘贴一个“[”,在结尾粘贴一个“]”。

答案 1 :(得分:1)

我假设您的x是向量的每个第一个坐标和第二个坐标的y的串联。

假设你有这样的输出。

output <- "[(9.010658025741577, 2.8047988414764404), (9.242822885513306, 2.66866397857666), (9.263759851455688, 2.6707050800323486), (9.515105962753296, 2.5500648021698)]"

您可以执行以下操作。

clean_output <- gsub("\\[|\\]|\\(|\\)", "", output) # remove brackets and parenthesis
coord_mat <- matrix(unlist(strsplit(clean_output, ", ")),ncol = 2, byrow = T)
# retrieve coordinates as a matrix arranged the way you like
x <- paste0("[", paste(coord_mat[,1], collapse = ", "), "]")
y <- paste0("[", paste(coord_mat[,2], collapse = ", "), "]")

答案 2 :(得分:1)

您可以尝试以下操作:

#Loading text
text <- "[(9.010658025741577, 2.8047988414764404), (9.242822885513306, 2.66866397857666), (9.263759851455688, 2.6707050800323486), (9.515105962753296, 2.5500648021698)]"

#Extracting the numbers from the string and creating a tbl_df
text <- text %>% 
  stringr::str_match_all("[0-9]+") %>%
  unlist() %>% 
  as.numeric() %>% 
  tbl_df()

#Creating new tbl_df for odd and even 
EvenNumbers <- text[floor(text$value) %% 2 == 0, ] 
OddNumbers <- text[floor(text$value) %% 2 == 1, ] 
相关问题