Home > Mobile >  How can we use R to loop over the different lines contained in the text file and convert it to a lis
How can we use R to loop over the different lines contained in the text file and convert it to a lis

Time:12-23

My Python homework:

  1. Use the open() built-in function to open the file named dialog.txt and assign it to a variable named file.
  2. Using the list() function assign all lines contained in a file to a variable named lines.
  3. Close the file using the close() method.

My Python answer that is working:

file = open("dialog.txt", "r")
lines = list(file)
file.close()

How can we do the same with R?

This is the list that the Python code produces.

enter image description here

Can you help with me with R? I am curious. It is not part of the homework. I do not know what to do after this:

# Read a txt file, named "dialog.txt"
file <- read.delim("dialog.txt")

CodePudding user response:

Easiest solution:

lines <- as.list(readLines(path))

To your question:

as.list(as.character(unlist(read.delim("test.csv", head=FALSE, sep="\n"))))

would also give lines.

But all outputs are without "\n" at the end.

I would highly recommend, however, to leave the as.list() away. R is not Python.

For R you have to follow: Whenever you can use a vector, you should. Because the performance of vectors is 10 if not 100x better than that of lists (whenever the number of element gets very high).

  •  Tags:  
  • r
  • Related