问题
I have a matrix. If an element of the matrix is greater than 400, then I would like the element to become zero. If an element of the matrix is less than 400, then I would like to multiply the element by three.
Here is how to reproduce my matrix:
structure(c(122, 948, 952, 100,
942, 150, 150, 149,
244, 220, 437, 395,
356, 473, 434, 335,
357, 371, 590, 553,
520, 491, 426, 426,
427, 177, 284, 338,
391, 290, 345, 399,
143, 193, 136, 121,
122, 187, 177, 544), .Dim = c(10L, 4L), units = structure(list(
numerator = "m", denominator = character(0)), class = "symbolic_units"), class = "units")
回答1:
With Matrix
being your data:
for(i in 1:dim(Matrix)[2])
{
Matrix[,i] <- ifelse(Matrix[,i]>400,0,
ifelse(Matrix[,i]<400,3*Matrix[,i],Matrix[,i]))
}
[,1] [,2] [,3] [,4]
[1,] 366 0 0 1035
[2,] 0 1185 0 1197
[3,] 0 1068 0 429
[4,] 300 0 0 579
[5,] 0 0 0 408
[6,] 450 1005 531 363
[7,] 450 1071 852 366
[8,] 447 1113 1014 561
[9,] 732 0 1173 531
[10,] 660 0 870 0
来源:https://stackoverflow.com/questions/63117901/changing-values-in-a-matrix-depending-on-whether-they-are-above-of-below-a-certa