I'm currently working on an assignment, in which I need to write a function that will read certain (provided in the assignment) files with the extension .dat. In said files, there is some data about graphs. The problem, however, lies in the way the data is stored inside the file.
They look like this:
{1, {2, 3, 4, 5, 8}}
{2, {1}}
{3, {1, 6, 7}}
{4, {1}}
{5, {1}}
{6, {3, 9, 10}}
{7, {3}}
{8, {1}}
{9, {6}}
{10, {6}}
The first number is the graph vertex, the second number marks the other vertexes with which the first one is connected.
So for example {1, {2, 3, 4, 5, 8}} means that the vertex number 1 is connected with vertexes 2 3 4 5 8.
The goal is to create a function that would provide a list in which every cell would contain a list with information about which vertex it is and what are its connections, like this:
list( node = 1, connections = c( 2, 3, 4, 5, 8)) list( node = 2, connections = c( 1))
My approach so far was following:
Since I didn't know how to read that file and skip the brackets I figured I will just read the file in, remove all non-numeric signs and then using a loop go through each of them and divide the remaining number and then just have the divided number put into separate columns.
I got it to work.. somewhat, the problem is that I didn't take it into account that there can be more than 9 rows in given file, so taking the first digit only works for 1-9. A workaround would be using an if statement, but before diving into that I thought I'll ask around for ideas.
readInGraph <- function(path){
read.csv(path, header=FALSE, sep=";")
}
Beginning of the required function, reading the graph file
gSmall <- readInGraph( path = "./graph_small.dat")
gSmall
unlisting the data, removing non numerics
unlisted_file <- unlist(gSmall)
unlisted_file
numerics <- gsub("[^0-9\\.]", "", unlisted_file)
numerics <- as.numeric(numerics)
filling in the table with just numbers
df <- numeric(length(numerics))
for (i in 1:length(numerics)) {
df[i] <- numerics[i]
}
mentioned loop made in order to divide the text and just get the first character
df1 <- numeric(length(numerics))
for (i in 1:length(numerics)) {
df1[i] <- substr(df[i],1,1)
}
Important note, edit: I cannot use any libraries that are not included in base R, it has to be as "raw" as possible.
This is the first time I'm using stackoverflow so I don't know if I can upload the file with code somewhere somehow. If I need to clarify anything, please do let me know.
Thanks in advance!