在R中导入和清理文本文件

时间:2018-05-31 23:06:06

标签: r read.table

我在文本文件中有以下格式的数据。

(0.00,1.00),(1.00,0.93),(2.00,0.86),(3.00,0.8),(4.00,0.75),(5.00,0.7),(6.00,0.65),(7.00,0.6) ,(8.00,0.56),(9.00,0.52),(10.0,0.49)

括号内的第一个元素是x,第二个元素是y。如何使用以下格式创建矩阵。

    x    y
    0    1
    1    0.93
    2    0.86
    3    0.8
    4    0.75

我尝试过read.table的变种,但没有成功。非常感谢任何帮助。

2 个答案:

答案 0 :(得分:1)

首先,我们将您的字符串保存为文件,以便解决方案可重现:

str0 <- "(0.00, 1.00), (1.00, 0.93), (2.00, 0.86), (3.00, 0.8), (4.00, 0.75), (5.00, 0.7), (6.00, 0.65), (7.00, 0.6), (8.00, 0.56), (9.00, 0.52), (10.0, 0.49)"
file1 <- "str1.xt"
write(str0,file1)

溶液:

x <-  scan(file1, character())
x <-  as.numeric(gsub("[(,)]","",x))
x <-  matrix(x,ncol = 2,byrow = TRUE,dimnames = list(NULL,c("x","y")))
as.data.frame(x)
 # x    y
 # 1   0 1.00
 # 2   1 0.93
 # 3   2 0.86
 # 4   3 0.80
 # 5   4 0.75
 # 6   5 0.70
 # 7   6 0.65
 # 8   7 0.60
 # 9   8 0.56
 # 10  9 0.52
 # 11 10 0.49

替代解决方案:

x <- gsub("), (",", ",scan(file1, character(),sep="_"),fixed = T)
as.data.frame(eval(parse(text=paste0("matrix(c",x,",ncol = 2,byrow = TRUE,dimnames = list(NULL,c('x','y')))"))))

答案 1 :(得分:0)

这样的事情怎么样?

text <-
    "(0.00, 1.00), (1.00, 0.93), (2.00, 0.86), (3.00, 0.8), (4.00, 0.75), (5.00, 0.7), (6.00, 0.65), (7.00, 0.6), (8.00, 0.56), (9.00, 0.52), (10.0, 0.49)";

do.call(rbind, lapply(
    gsub("(\\s*\\(|\\)\\s*)", "", unlist(strsplit(text, split = "),"))),
    function(x) as.numeric(unlist(strsplit(x, ", ")))))
#      [,1] [,2]
# [1,]    0 1.00
# [2,]    1 0.93
# [3,]    2 0.86
# [4,]    3 0.80
# [5,]    4 0.75
# [6,]    5 0.70
# [7,]    6 0.65
# [8,]    7 0.60
# [9,]    8 0.56
#[10,]    9 0.52
#[11,]   10 0.49

说明:我们首先在"),"上拆分条目以分隔行,然后在", "上将每个条目清单分隔为每行的列条目。

或者避免do.call(rbind, ...)

t(sapply(
    gsub("(\\s*\\(|\\)\\s*)", "", unlist(strsplit(text, split = "),"))),
    function(x) as.numeric(unlist(strsplit(x, ", ")))))
#           [,1] [,2]
#0.00, 1.00    0 1.00
#1.00, 0.93    1 0.93
#2.00, 0.86    2 0.86
#3.00, 0.8     3 0.80
#4.00, 0.75    4 0.75
#5.00, 0.7     5 0.70
#6.00, 0.65    6 0.65
#7.00, 0.6     7 0.60
#8.00, 0.56    8 0.56
#9.00, 0.52    9 0.52
#10.0, 0.49   10 0.49