I am trying to use stdindata to read in R. I want to read data in the following format:
5 #rows matrix A
7 #cols matrix A
0 1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30 31 32 33 34
3 #rows matrix B
4 #cols matrix B
0 1 2 3
4 5 6 7
8 9 10 11
100 #param1
-7 #param2
9 #param3
An example of how I would like to read the data is best illustrated by the following c code:
#include <stdio.h>
#include <stdlib.h>
int* readMatrix(int rows, int cols) {
int* matrix = (int*) malloc(rows*cols*sizeof(int));
for (int i = 0; i < rows*cols; ++i) {
scanf("%d", &matrix[i]);
}
return matrix;
}
int main() {
int a_rows, a_cols;
int b_rows, b_cols;
int *a, *b;
int param1, param2, param3;
scanf("%d %d", &a_rows, &a_cols);
a = readMatrix(a_rows, a_cols);
scanf("%d %d", &b_rows, &b_cols);
b = readMatrix(b_rows, b_cols);
scanf("%d %d %d", ¶m1, ¶m2, ¶m3);
return 0;
}
My "equivalent" R code looks something like this:
a_rows <- scan(file="stdin", what=integer(0), n=1);
a_cols <- scan(file="stdin", what=integer(0), n=1);
A <- matrix(scan(file="stdin", n = a_rows*a_cols), a_rows, a_cols, byrow = TRUE)
b_rows <- scan(file="stdin", what=integer(0), n=1);
b_cols <- scan(file="stdin", what=integer(0), n=1);
B <- matrix(scan(file="stdin", n = b_rows*b_cols), b_rows, b_cols, byrow = TRUE)
param1 <- scan(file="stdin", what=integer(0), n=1);
param2 <- scan(file="stdin", what=integer(0), n=1);
param3 <- scan(file="stdin", what=integer(0), n=1);
Of course, this does not work, and I get the following output when I run the R script:
Read 1 item
Read 0 items
Read 0 items
Error in matrix(scan(file = "stdin", n = a_rows * a_cols), a_rows, a_cols, :
invalid 'ncol' value (too large or NA)
Execution halted
In fact, if I try to read only the first two values:
a_rows <- scan(file="stdin", what=integer(0), n=1);
a_cols <- scan(file="stdin", what=integer(0), n=1);
I get the following output:
Read 1 item
Read 0 items
Does anyone have a good solution to this problem? I am trying to find additional information about a function scanbut cannot find anything about why I get this behavior.
EDIT 1
I am running R version 3.1.0
R version 3.1.0 (2014-04-10) -- "Spring Dance"
Copyright (C) 2014 The R Foundation for Statistical Computing
Platform: x86_64-unknown-linux-gnu (64-bit)
EDIT 2
I found a solution, the R code is as follows:
sin <- file("stdin");
open(sin);
a_rows <- scan(sin, what=integer(0), n=1);
a_cols <- scan(sin, what=integer(0), n=1);
A <- matrix(scan(sin, n = a_rows*a_cols), a_rows, a_cols, byrow = TRUE)
b_rows <- scan(sin, what=integer(0), n=1);
b_cols <- scan(sin, what=integer(0), n=1);
B <- matrix(scan(sin, n = b_rows*b_cols), b_rows, b_cols, byrow = TRUE)
param1 <- scan(sin, what=integer(0), n=1);
param2 <- scan(sin, what=integer(0), n=1);
param3 <- scan(sin, what=integer(0), n=1);
stdin, .