0

I have a df ( my_df : n by m ) and also a matrix ( my_mat : n by m again ).
I want to change the value of my_df[j,i] if my_mat[j,i] is not zero, and leave it as is, if my_mat[j,i] is zero.
then I want to return the index of the column of my_df which contains the highest value in that row, in a grp column.

for(j in 1:nrow(my_df)){
  for(i in 1:nclo(my_df){
    if(my.mat[j,i]!=0)
      {my.df[j,i] <- (my.mat[j,i])/(crossprod(my.vec,my.mat[j,]))
    }

    my.df$grp[j] <- which.max(my.df[j,])
  }
}

I notice, my code does not leave the my.df[j,i] untouched if my.mat[j,i] is zero. how can I solve this?

sschwei1
  • 362
  • 2
  • 11
Mathica
  • 1,241
  • 1
  • 5
  • 17
  • Maybe change the part `my.mat[j,i]!=0` to `!all.equal(my.mat[j,i], 0)` – GKi Jul 21 '21 at 12:12
  • Have also a look at: [Numeric comparison difficulty in R](https://stackoverflow.com/q/2769510/10488504) – GKi Jul 21 '21 at 12:14
  • @GKi , it did not do the job, unfortunately. :( – Mathica Jul 21 '21 at 12:33
  • Maybe because you use one `my.df` and other `my_df`. In addition there are some other syntactical failures. – GKi Jul 21 '21 at 12:41
  • @GKi, thank for pointing this out, but no actually I rewrote my code in a simpler version here. just a typo here but not on my actual code. – Mathica Jul 21 '21 at 12:46

1 Answers1

0

I can not observe that the code does not leave the my_df[j,i] untouched if my.mat[j,i] is zero. I removed some errors so the code will run:

set.seed(42)
my.mat <- matrix(sample(0:9, 6), 2, 3)
my_df <- as.data.frame(my.mat)
my.vec <- 1:3

my_df[my.mat == 0]
#[1] 0

for(j in 1:nrow(my.mat)) {
  for(i in 1:ncol(my.mat)) {
    if(my.mat[j,i]!=0) {
      my_df[j,i] <- (my.mat[j,i])/(crossprod(my.vec,my.mat[j,]))
    }
    my_df$grp[j] <- which.max(my_df[j,])
  }
}

my_df[1:3][my.mat == 0]
#[1] 0
GKi
  • 37,245
  • 2
  • 26
  • 48