What I am trying to do: 1- Read file contents into a matrix (with two features/columns: ID and Text) 2- Collapse rows that have the same ID, or, if not possible, create a new matrix with the collapsed data 3- Output a .txt file in the wd that has the ID as a name and the Text as content
Here is what I did:
#set working directory and get file_list
myvar <- matrix(0,nrow=0,ncol=2)
colnames(myvar) <- c("PID","Seq")
for(file in file_list)
{
print(file)
Mymatrix <- as.matrix(read.table(file))
for(i in 1:length(Mymatrix[,1]))
{
if(Mymatrix[i,1] %in% myvar[,1])
{
myvar[which(myvar[,1] == Mymatrix[i,1]) ,2] <- paste(myvar[which(myvar[,1] == Mymatrix[i,1]),2],Mymatrix[i,2])
}else{
myvar <- rbind(myvar,c(Mymatrix[i,1],Mymatrix[i,2]))
}
}
}
Performance is of issue, cf profvis output here:
Here is a reproducible code:
#Input:
a <- matrix(0,ncol=2, nrow=0)
colnames(a) <- c("id","text")
#possible data in the matrix after reading one file
a <- rbind(a,c(1,"4 5 7 7 8 1"))
a <- rbind(a,c(1,"5 5 1 3 7 5 1"))
a <- rbind(a,c(7,"5 5 1 3 7 5 1"))
a <- rbind(a,c(5,"1 3 2 25 5 1 3 7 5 1"))
#expected output after processing
> a
id text
[1,] "1" "4 5 7 7 8 1 5 5 1 3 7 5 1"
[2,] "7" "5 5 1 3 7 5 1"
[3,] "5" "1 3 2 25 5 1 3 7 5 1"
Note: The order of the text after collapsing rows was kept: (4 5 7 7 8 1
followed by 5 5 1 3 7 5 1
for ID=1
)
As mentioned before the biggest issue is performance: the way I'm currently doing it takes way much time. Is there any solution with something like aggregate or apply?