Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

creating a matrix/dataframe with two for loops in R

This is my first post on SO, so be kind!

My question is vaguely related to this one: Double for loop in R creating a matrix

I want to create a matrix/dataframe and the approach my mind has chosen is to nest two for loops, one to create the first row and the second to repeat it for the rows I nedd.

I could successfully create the first loop, but I can't seem to iterate it for the number of rows I need.

I'm sure that there is a better way to do this, anyway, this is the for loop that gives the result I need for the first row:

x <- character(0)
for(j in 1:18){
    x <- c(x, sum(it_mat[1, 2:26] == j))
}

it_mat is a matrix of 417 rows and 26 columns, where the first column is a string vector with various names and the subsequent columns are randomly generated numbers from 1 to 18.

Here's the first row:

[1,] "Charlie" "14" "3"  "9"  "14" "3"  "9"  "11" "11" "18"  "17"  "16"  "5"   "18"  "6"   "10"  "3"   "9"   "9"   "3"   "18"  "12"  "8"   "5"   "5"  "4"

I want to create a matrix/df where I count how many times, for each name, each number appearead.

The for loop I created above gives me the result I want for the first row:

x
[1] "0" "0" "4" "1" "3" "1" "0" "1" "4" "1" "2" "1" "0" "2" "0" "1" "1" "3"

I really can't iterate it for the subsequent rows with another for loop, there must be something very mundane that I do wrong.

This is my best attempt:

tr_mat <- matrix(, nrow = 147, ncol = 18)
for(i in 1:147){
    x <- character()
    for(j in 1:18){
        x <- c(x, sum(it_mat[i, 2:26] == j))
    }
    tr_mat <- rbind(tr_mat, x)
}

I went on it all afternoon and now I give up and reach out to you, before you give me the correct way to do it, please explain what I'm doing wrong in the nested for loops try, I might learn something.

I hope I explained myself, sorry if I've been too verbose. Thanks for your time.

like image 946
goingdeep Avatar asked Jan 27 '26 06:01

goingdeep


1 Answers

@RuiBarradesh has pin-pointed the actual problem in OP last attempt. There is another way to fix the OP code using rbind.

# Do not create rows at this place. Let the rows be added with rbind
tr_mat <- matrix(nrow = 0, ncol = 18)   #(, nrow = 147, ncol = 18)
for(i in 1:147){
  x <- character()
  for(j in 1:18){
    x <- c(x, sum(it_mat[i, 2:26] == j))
  }
  tr_mat <- rbind(tr_mat, x)
}

tr_mat      # This will display correct result too
like image 50
MKR Avatar answered Jan 29 '26 21:01

MKR



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!