Etibar - a tea bar
Etibar - a tea bar

Reputation: 1962

Importing a txt file when number of columns isn't known

I need to read data from txt file into data frame. Number of columns aren't known, either datas are different. It may be any number. Here in example I showed 5 columns. But in real data it isn't known. It maybe 15 or 30 or more.

3401 6193 6237 
1556 2502 2883 4431 6119 
643 3723 

I expect something like

  V1             V2             V3      V4           V5  
3401            6193           6237     NA            NA
1556            2502           2883    4431           6119 
643             3723            NA      NA             NA

I need data in data.frame or in matrix.

Upvotes: 2

Views: 107

Answers (1)

desc
desc

Reputation: 1210

Use count.fields to find the length of each new table:

df.col.length = max(count.fields(test.txt,sep=" "))

Then you can use read.table with fill = TRUE to get your table into R:

test.df = read.table(test.txt, sep = " ", col.names = c(1:df.col.length), fill = TRUE)

Upvotes: 1

Related Questions