0

I see a related question has already been asked, but it misses my particular use case.

If I have an org-mode table with some data, and I want to import it into an R session, using read.table. However, I get an error saying Error in read.table(test) 'file' must be a character string or connection:

#+TBLNAME: my_tab
|     x | y |
|-------+---|
|   1.2 | d |
| 234.3 | e |
|    32 | f |
|    64 | g |
|-------+---|

#+begin_src R :var test=my_tab :results output :exports none :eval never-export
my_df <- read.table(test)
#+end_src

#+RESULTS:
: Error in read.table(test) : 
:   'file' must be a character string or connection

But the following does work:

#+begin_src R :var test=my_tab :results output :exports none :eval never-export
my_df <- data.frame(test)
#+end_src

I'm not quite sure what it is that stops the import from happening in one case but not the other; perhaps it's an issue with type conversion or specifying the correct separator, but no changes I make seem to fix it.

Is there some way to stop the error and just use read.table()?

nonreligious
  • 473
  • 2
  • 14
  • Are you sure this is an Org mode question? It feels like an R question to me: you need to read the documentation for `read.table` and see what it needs. – NickD Jan 19 '23 at 15:38
  • In fact, the `read.table` doc says: "Reads a **file** in table format ...", so you'd have to save the Org table into a file before you can use the file in `read.table`. – NickD Jan 19 '23 at 15:44
  • @NickD Well, I asked here as I think it's a reasonable assumption the proportion of org-mode users who work with R is greater than the proportion of R users who use org-mode -- see all the examples on Worg. As for the `read.table` documentation, a little later it says `Alternatively, ‘file’ can be a readable text-mode connection..`, which is what the variable containing the table should be... – nonreligious Jan 20 '23 at 13:42
  • No, it is not: it's literally the data in the table, not a connection to some process that produces the table. You should be able to use the dataframe produced from the in-memory data to save a file that you can then read with `read.table`. But again all of these questions are `R`-specific. This has nothing to do with Org mode. – NickD Jan 20 '23 at 14:52
  • Hmm, I see. I was confused by the fact that in the R session buffer, I see `test <- local({con <- textConnection( "\"x\" \"y\" \"1.2\" \"d\" \"234.3\" \"e\" \"32\" \"f\" \"64\" \"g\"" ) res <- utils::read.table( con, header = FALSE, row.names = NULL, sep = "\t", as.is = TRUE ) close(con) res})`, but I see that `typeof(test)` is `list`, and what seems to be happening is that a temporary text connection is being created to read the table into the `test` variable. I guess what I wanted to do is to somehow skip the creation of `con`, or directly pipe it into `read.table()`. – nonreligious Jan 21 '23 at 15:03

0 Answers0