列数未知时导入 txt 文件
Importing a txt file when number of columns isn't known
我需要从 txt 文件中读取数据到数据框中。列数未知,或者数据不同。它可以是任何数字。在示例中,我展示了 5 列。但在实际数据中,它是未知的。它可能是 15 或 30 或更多。
3401 6193 6237
1556 2502 2883 4431 6119
643 3723
我期待
V1 V2 V3 V4 V5
3401 6193 6237 NA NA
1556 2502 2883 4431 6119
643 3723 NA NA NA
我需要 data.frame 或矩阵中的数据。
使用count.fields
求出每个新table的长度:
df.col.length = max(count.fields(test.txt,sep=" "))
然后你可以使用 read.table 和 fill = TRUE 让你的 table 进入 R:
test.df = read.table(test.txt, sep = " ", col.names = c(1:df.col.length), fill = TRUE)
我需要从 txt 文件中读取数据到数据框中。列数未知,或者数据不同。它可以是任何数字。在示例中,我展示了 5 列。但在实际数据中,它是未知的。它可能是 15 或 30 或更多。
3401 6193 6237
1556 2502 2883 4431 6119
643 3723
我期待
V1 V2 V3 V4 V5
3401 6193 6237 NA NA
1556 2502 2883 4431 6119
643 3723 NA NA NA
我需要 data.frame 或矩阵中的数据。
使用count.fields
求出每个新table的长度:
df.col.length = max(count.fields(test.txt,sep=" "))
然后你可以使用 read.table 和 fill = TRUE 让你的 table 进入 R:
test.df = read.table(test.txt, sep = " ", col.names = c(1:df.col.length), fill = TRUE)