...

/

Solution Review: Handling TXT files

Solution Review: Handling TXT files

In this review, we provide a detailed analysis of the solution to this problem.

Solution: Input/Output from File

Press + to interact
R
Files
evenOdd <- function(myVector) # a function that returns a vector
# whose each element tells even or odd corresponding to input vector
{
myOutputVector <- vector("character", 0)
for(i in myVector)
{
if(as.integer(i) %% 2 == 0)
{
myOutputVector <- c(myOutputVector, "even")
}
else
{
myOutputVector <- c(myOutputVector, "odd")
}
}
return(myOutputVector)
}
# Driver Code
path <- "data.txt"
fileData <- file(path, open = "r") # open the file located in path
lines <- readLines(fileData) # read lines of the file
myVector <- vector("numeric", 0) # vector to store data
for (i in 1:length(lines)) # iterate over all the lines
{
myVector <- c(myVector, lines[i]) # append lines in myVector
}
result <- evenOdd(myVector) # store output in result
write(result, "output/outData.txt") # write result on file

Explanation

In this example, we ...