R 从单个文本文件中读取多个表?
我有一个.txt文件,其中有许多表。有没有一种方法可以将这些数据读入自己的数据帧中?每个“表”前面都有一行标题,因此我可以搜索这些标题R 从单个文本文件中读取多个表?,r,text-files,R,Text Files,我有一个.txt文件,其中有许多表。有没有一种方法可以将这些数据读入自己的数据帧中?每个“表”前面都有一行标题,因此我可以搜索这些标题 谢谢您的帮助。您需要读取整个文件,然后解析它以查找表头或空行。我会将标题设置为您设置的变量,并将其置于脚本顶部,以便您在更改txt文件中的表时轻松地进行更改 简单的谷歌搜索返回了这个。 对我来说非常有效 > x <- readLines(textConnection("1 + Pietje + I1 I2 Value + 1 1 0.11 + 1
谢谢您的帮助。您需要读取整个文件,然后解析它以查找表头或空行。我会将标题设置为您设置的变量,并将其置于脚本顶部,以便您在更改txt文件中的表时轻松地进行更改 简单的谷歌搜索返回了这个。 对我来说非常有效
> x <- readLines(textConnection("1
+ Pietje
+ I1 I2 Value
+ 1 1 0.11
+ 1 2 0.12
+ 2 1 0.21
+
+ 2
+ Jantje
+ I1 I2 I3 Value
+ 1 1 1 0.111
+ 3 3 3 0.333"))
> closeAllConnections()
> start <- grep("^[[:digit:]]+$", x)
> mark <- vector('integer', length(x))
> mark[start] <- 1
> # determine limits of each table
> mark <- cumsum(mark)
> # split the data for reading
> df <- lapply(split(x, mark), function(.data){
+ .input <- read.table(textConnection(.data), skip=2, header=TRUE)
+ attr(.input, 'name') <- .data[2] # save the name
+ .input
+ })
> # rename the list
> names(df) <- sapply(df, attr, 'name')
> df
$Pietje
I1 I2 Value
1 1 1 0.11
2 1 2 0.12
3 2 1 0.21
$Jantje
I1 I2 I3 Value
1 1 1 1 0.111
2 3 3 3 0.333
>x closeAllConnections()
>开始标记[开始]#确定每个表的限制
>标记#拆分数据以便读取
>好的,谢谢。所以我用行来阅读整个内容,我会使用readline(因为我知道我会得到什么),然后使用段作为输入:例如read.table(textConnection(lines[2:33])