使用不同的分隔符将数据读入R中

时间:2017-10-09 12:44:45

标签: r read.table

我正在尝试将一个文件读入R中,在第一行中有不同的分隔符,空格作为分隔符,但是从第二行到第一行之间的最后一行,第二列有一个空格,第二行和第二列之间相同第三,然后所有的两个块,零和一个应该是不同的列。 任何提示?!

ID Chip AX-77047182 AX-80910836 AX-80737273 AX-77048714 AX-77048779 AX-77050447 
3811582 1 2002202222200202022020200200220200222200022220002200000201202000222022
3712982 1 2002202222200202022020200200220200222200022220002200000200202000222022
3712990 1 2002202211200202021011100101210200111101022121112100111110211110122122
3713019 1 2002202211200202021011100101210200111101022121112100111110211110122122
3713025 1 2002202211200202021011100101210200111101022121112100111110211110122122
3713126 1 2002202222200202022020200200220200222200022220002200000200202000222022

2 个答案:

答案 0 :(得分:0)

当然不是最优雅的解决方案,但您可以尝试以下方法。如果我已正确理解您的示例数据,则您未提供零/一/二行所需的所有列名称(AX-77047182,...)。如果我的理解是错误的,下面的方法将不会产生所需的结果,但仍可能帮助您找到解决方法 - 您可能只是在第二个拆分命令中调整分隔符。我希望这有帮助...

#read file as character vector
chipstable <- readLines(".../chips.txt")

#extact first line to be used as column names
tablehead <- unlist(strsplit(chipstable[1], " "))

#split by first delimiter, i.e., space
chipstable <- strsplit(chipstable[2:length(chipstable)], " ")

#split by second delimiter, i.e., between each character (here number) 
#and merge the two split results in one line
chipstable <- lapply(chipstable, function(x) {

  c(x[1:2],  unlist(strsplit(x[3], "")))

})

#combine all lines to a data frame
chipstable <- do.call(rbind, chipstable)

#assign column names
colnames(chipstable) <- tablehead

#turn values to numeric (if needed)
chipstable <- apply(chipstable, 2, as.numeric)

答案 1 :(得分:-1)

你可以试试...... read(pattern = " || 1 ", recursive = TRUE) 制作一个绑定后

例如:

data <- "ID Chip AX-77047182 AX-80910836 AX-80737273 AX-77048714 AX-77048779 AX-77050447 
3811582 1 2002202222200202022020200200220200222200022220002200000201202000222022
3712982 1 2002202222200202022020200200220200222200022220002200000200202000222022
3712990 1 2002202211200202021011100101210200111101022121112100111110211110122122
3713019 1 2002202211200202021011100101210200111101022121112100111110211110122122
3713025 1 2002202211200202021011100101210200111101022121112100111110211110122122
3713126 1 2002202222200202022020200200220200222200022220002200000200202000222022"

teste <- strsplit(data, split = "\n")

for(i in seq(1, length(teste[[1]]),1)) {
  if (i==1) {
    dataOut <- strsplit(teste[[1]][i], split = " ")
    print(dataOut)
  } else
    dataOut <- strsplit(teste[[1]][i], split = " 1 ")
  print(dataOut)
}