I'm new to R Programming.
I have two lists one list contains usernames. Another list contains pages visited by each user
user: AAA BBB CCC DDD
records:
page 1 AAA
page 2 BBB
page 3 AAA
page 4 BBB
page 1 BBB
page 4 AAA
I need to gather all pages visited by each user
Output required:
Pages visited by AAA page1,page 3, page 4
Pages visited by BBB page 2, page4, page 1
I am trying to store the pages visited by each user in a matrix
For instance, columns in row 1 of the matrix will contain pages viewed by user 1 and so on
Please look at my code below:
k <- 0
out <- matrix(NA, nrow=100, ncol=50) #my final output matrix
for (i in users)
{
k <- k+1
p <- 0
for (j in records)
{
x<-(strsplit(j, "\t"))
if(x[[1]][2]== i) #gather all pages visited by a same user
{
p <- p+1
out[k,p]=c(x[[1]][1])
}
}
x <- 0
#here i need to remove unused columns in row k
}
out <- out[1:(k),] #remove unused rows in a matrix
print (out)
Output I get
page1 page3 page4 NA NA NA .... NA
page2 page4 page1 NA NA NA .... NA
Final Matrix required:
page1 page3 page4
page2 page4 page1