I'm new to R and have encountered a problem. I'm trying to fill a matrix ("m") based on the data in another dataframe ("razdeljena1") - all of the column and row names or "m" are matching the names found in first and second column in "razdeljena1".
m <- matrix(1:729, byrow = TRUE, nrow = 27,
dimnames = list(c("PES", "MAčKA", "VTÁK","HORA","STROM","RIEKA","SLNKO","MÄSO","SYR","VODA","CHLIEB","KLADIVO","METLA","PERO","NÔŽ","POSTEĽ","STÔL","SKRIŇA","LAMPA","TOPÁNKA","NOHAVICE","KLOBÚK","DÁŽDNIK","VEDRO","FĽAŠA","VRECE","KONZERVA"),
c("PES", "MAčKA", "VTÁK","HORA","STROM","RIEKA","SLNKO","MÄSO","SYR","VODA","CHLIEB","KLADIVO","METLA","PERO","NÔŽ","POSTEĽ","STÔL","SKRIŇA","LAMPA","TOPÁNKA","NOHAVICE","KLOBÚK","DÁŽDNIK","VEDRO","FĽAŠA","VRECE","KONZERVA")))
m <- replace(m, 1:729, NA)
Here are the first 12 observations in razdeljena1
1 2 rating.response
[1,] "SYR" "KLADIVO" "1"
[2,] "LAMPA" "DÁŽDNIK" "1"
[3,] "CHLIEB" "KLOBÚK" "1"
[4,] "STROM" "KONZERVA" "1"
[5,] "PERO" "NÔŽ" "1"
[6,] "STÔL" "DÁŽDNIK" "1"
[7,] "STROM" "VODA" "1"
[8,] "DÁŽDNIK" "KONZERVA" "1"
[9,] "PERO" "POSTEĽ" "1"
[10,] "HORA" "VODA" "1"
[11,] "LAMPA" "FĽAŠA" "1"
[12,] "STROM" "SKRIŇA" "1"
For this I created a while loop that would read every line and extract necessary info and write it to the matrix.
a <- 1
while (a <379){
beseda1 <- razdeljena1[a,1]
beseda2 <- razdeljena1[a,2]
relat <- razdeljena1[a,3]
m[beseda1, beseda2] <- relat
m[beseda2, beseda1] <- relat
a <- a+1
}
The loop works well for the first 9 iterations (and writes into a matrix correctly) and then returns an error Error in [<-(*tmp*, beseda1, beseda2, value = relat) : subscript out of bounds.
I have looked into the error and the answer to it says that I'm trying to access a column or a row that does not exist - however: when I try to access the cell outside of the loop (with the identically defined coordinates) it in fact returns the correct cell.
example:
The error occurs when beseda1 = "PERO"
and beseda2 = "POSTEĽ"
; however when I try to change it outside of the loop it works just fine:
beseda1 <- "PERO"
beseda2 <- "POSTEĽ"
m[beseda1, beseda2] <- 1
m[beseda2, beseda1] <- 1
I have also tried to see if this is the only pair that would cause problems (by starting a while loop with a number greater than 9) and got the the same error after some iterations.