CRYPTIC
CRYPTIC

Reputation: 11

How to read data

I am quite a newbie to the r language i wanted to read the following input but Ihave no idea how to proceed:

m n
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16

I wanted to read the following input into 6 categories

  1. m
  2. n
  3. c(1,5,9,13)
  4. c(2,6,10,14)
  5. c(3,7,11,15)
  6. c(4,8,12,16)

I tried the following code but it doesn't seem to work

f <- file("stdin")
r <- file("stdin")

data1 = scan(file = r,skip = 1)
data1 <- split(data1, " ")

data2 = scan(file = f ,nlines =1)
data2 <- split(data2, " ")

o1 = data2[1]
o2 = data2[2]

It always seems to give

"Read 0 items"

for data2.

Upvotes: 0

Views: 86

Answers (1)

G. Grothendieck
G. Grothendieck

Reputation: 269586

Use read.table twice where Lines is given in the Note at the end.

mn <- read.table(text = Lines, nrows = 1, as.is = TRUE)
DF <- read.table(text = Lines, skip = 1)

giving:

mn
##   V1 V2
## 1  m  n

mn[[1]]
## [1] "m"

mn$V1 # same
## [1] "m"


DF
##   V1 V2 V3 V4
## 1  1  2  3  4
## 2  5  6  7  8
## 3  9 10 11 12
## 4 13 14 15 16

DF[[1]]
## [1]  1  5  9 13

DF$V1   # same
## [1]  1  5  9 13

A list made up of the 6 components is:

unname( c(mn, DF) )
## [[1]]
## [1] "m"
## 
## [[2]]
## [1] "n"
## 
## [[3]]
## [1]  1  5  9 13
## 
## [[4]]
## [1]  2  6 10 14
## 
## [[5]]
## [1]  3  7 11 15
##
## [[6]]
## [1]  4  8 12 16

scan

If you prefer to use scan, as in the question, then assuming that the lines all have the same number of fields except for the first line, get the field counts, one per line, into counts and then use scan using those numbers:

counts <- count.fields(textConnection(Lines))
c( scan(text = Lines, what = "", nmax = counts[1], quiet = TRUE), 
   scan(text = Lines, what = as.list(numeric(counts[2])), skip = 1, quiet = TRUE) )
## [[1]]
## [1] "m"
## 
## [[2]]
## [1] "n"
##
## [[3]]
## [1]  1  5  9 13
## 
## [[4]]
## [1]  2  6 10 14
## 
## [[5]]
## [1]  3  7 11 15
##
## [[6]]
## [1]  4  8 12 16

Note

Assume the input is:

Lines <- "m n
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16"

Upvotes: 3

Related Questions