R: Apply cut using line breaks

I would like to transform the latent rating matrix into observable ratings.

This can be done by applying breakpoints / thresholds to the original matrix, resulting in a new, categorical matrix. It is simple, for example:

#latent variable matrix true=matrix(c(1.45,2.45,3.45, 0.45,1.45,2.45, 3.45,4.45,5.45) ,ncol=3,byrow=TRUE) #breaks for the cut function br=c(-Inf,1,2,3,4,Inf) #apply cut function to latent variable observed=apply(true,c(1,2),cut,breaks=br,labels=FALSE,include.lowest=TRUE) 

However, I need to make different breaks for each row of the original matrix . These thresholds are stored in the matrix:

 #matrix of breaks for the cut function br=matrix(c(-Inf,1,2,3,4,Inf, -Inf,1.5,2.5,3.5,4.5,Inf, -Inf,2,3,4,5,Inf) ,ncol=6,byrow=TRUE) 

That is, row 1 of br should serve as gaps for row 1 of the true matrix, and only for this row , row 2 of br is gaps for row 2 of truth, etc.

Using the following does not seem to do the job:

 for (i in 1:nrow(true)) { observed[i,]=apply(true[i,],c(1,2),cut,breaks=br[i,],labels=FALSE,include.lowest=TRUE) } 

Do you have any ideas? Is there a way to apply the corresponding br line to the corresponding true line and keep it in the same observation line?

Thank you very much in advance!

KN

+5
source share
2 answers

Using sapply by the number of lines (essentially just hiding the for loop), you get what you want:

 values = sapply(1:nrow(true), function(i) cut(true[i,], br[i,], labels=FALSE, include.lowest=TRUE))) values = t(values) 

Unfortunately, we need an extra transpose step to get the matrix correctly.


As for the for loop in your question, when you just multiply a line, i.e. true[i,] , we just get the vector. This will break the apply . To avoid the vector, you need an additional argument

 true[i,, drop=FALSE] 
+1
source

Some functional programming and a Map do the trick:

 splitLines = function(m) split(m, rep(1:nrow(m), ncol(m))) do.call(rbind, Map(cut, splitLines(true), splitLines(br), labels=F, include.lowest=T)) # [,1] [,2] [,3] #1 2 3 4 #2 1 1 2 #3 3 4 5 
+1
source

Source: https://habr.com/ru/post/1212192/


All Articles