0

#R--version: 4.1.1

Say I have a .txt-file with the content

a = c(1,2,3)
b = c(4,5,6)

and I want to read those statements into a list l such that

l = list(a = c(1,2,3),b=(4,5,6))

e.g

l = read_into_list_func("path/to/file/my_file.txt")

l$a
#1 2 3 

l$b
#4 5 6

I know how to read a txt-file but the issue is that instead of getting the command a=c(1,2,3) I get the string 'a=c(1,2,3)'.

Phil
  • 7,287
  • 3
  • 36
  • 66
CutePoison
  • 4,679
  • 5
  • 28
  • 63

1 Answers1

2

At its simplest, you can parse and evaluate the file as R code inside an environment, and convert that into a list:

e = new.env()
eval(parse('path/to/file.txt'), envir = e, encoding = 'UTF-8')
l = as.list(e)

(Don’t use source, it fails on Windows for non-ANSI encodings.)

… however, this is fairly inefficient and, more importantly, unsafe, because it executes arbitrary R code that’s in that file. If the file is provided by a malicious source and contains code to delete all your files, you do not want to execute that. Only use the above code for files of known, benign provenance.

Konrad Rudolph
  • 530,221
  • 131
  • 937
  • 1,214