R:重新格式化数据文件

时间:2015-07-16 20:37:25

标签: r reformatting

我怀疑是一个简单的数据重新格式化问题。数据文件(txt)的结构与观察数字分开,

1
45 65
78 56
2
89 34
39 55

所需的输出是,

1 45 65
1 78 56
2 89 34
2 39 55

非常感谢有关如何进行转换的建议。感谢。

1 个答案:

答案 0 :(得分:1)

我们可以使用>>> import numpy as np >>> np.genfromtxt(fileName) array([[ 1., 2., 3.], [ 4., 5., 6.]]) 阅读该文件。创建一个索引变量并拆分'lines'。删除列表元素的第一个元素,使用readLines读取文件,然后read.table

unnest

或者我们可以使用 lines <- readLines('file.txt') library(stringr) #remove leading/lagging spaces if any lines <- str_trim(lines) #create the index mentioned above based on white space indx <- !grepl('\\s+', lines) #cumsum the above index to create grouping indx1 <- cumsum(indx) #split the lines with and change the names of the list elements lst <- setNames(split(lines, indx1), lines[indx]) #Use unnest after reading with read.table library(tidyr) unnest(lapply(lst, function(x) read.table(text=x[-1])), gr) # gr V1 V2 #1 1 45 65 #2 1 78 56 #3 2 89 34 #4 2 39 55 方法

中的Map
base R
相关问题