假设你有这个矩阵:
m1 = matrix(0, 5, 5, dimnames = list(c("A", "B", "C", "D", "E"), c(1, 2, 3, 4, 5)))
m1[1,] = c(0,50,-10,0,10)
m1[2,] = c(0,0,0,10,50)
m1[3,] = c(0,0,10,100,4)
m1[4,] = c(40,40,100,1,0)
m1[5,] = c(1,0,100,0,60))
v1是阈值矢量:
v1 = matrix(0, 1, 5, dimnames = list(c("thresholds", c(1, 2, 3, 4, 5)))
v1[1,] = c(10,20,10,50,90)
我想在R中执行此操作并使用矢量化而不是循环... 首先是一个采用任何矩阵的函数:
#m is a matrix, #v is a vector of therholds
limitme <- function(x, v){
y <- matrix(0, ncol(x), nrow(x)) #matrix of 0s same size as x
for (i in 1:norow(x)){
for (j in 1:nocol(x){
if (x[i,j] >= v[j]) {
y[i,j] = 100 #this could be whatever but I am choosing 0 and 100
}
elif (x[i,j] < v[j]) {
y[i,j] = 0 #this could be whatever but I am choosing 0 and 100
}
}
}
return(y)
}
答案 0 :(得分:1)
m1 <-structure(c(0, 0, 0, 40, 1, 50, 0, 0, 40, 0, -10, 0, 10, 100,
100, 0, 10, 100, 1, 0, 10, 50, 4, 0, 60), .Dim = c(5L, 5L), .Dimnames = list(
c("A", "B", "C", "D", "E"), c("1", "2", "3", "4", "5")))
v1<-structure(c(10, 20, 10, 50, 90), .Dim = c(1L, 5L), .Dimnames = list(
"thresholds", c("1", "2", "3", "4", "5")))
#---------------------
> v1
1 2 3 4 5
thresholds 10 20 10 50 90
您可以使用扫描运算符为每列应用不同的阈值:
sweep(m1, 2, v1['thresholds',], ">")
1 2 3 4 5
A FALSE TRUE FALSE FALSE FALSE
B FALSE FALSE FALSE FALSE FALSE
C FALSE FALSE FALSE TRUE FALSE
D TRUE TRUE TRUE FALSE FALSE
E FALSE FALSE TRUE FALSE FALSE
和
> sweep(m1, 2, v1['thresholds',], ">")*100
1 2 3 4 5
A 0 100 0 0 0
B 0 0 0 0 0
C 0 0 0 100 0
D 100 100 100 0 0
E 0 0 100 0 0
您可以使用逻辑矩阵从两个选项中进行选择。 (可能更有趣,即难以在多个间隔之间进行选择。可能需要apply
与findInterval
一起使用。)这里我选择“A”和“B”但它可能有一直是数字值:
matrix( c("A", "B")[ 1+sweep(m1, 2, v1['thresholds',], ">") ], nrow=nrow(m1) )
[,1] [,2] [,3] [,4] [,5]
[1,] "A" "B" "A" "A" "A"
[2,] "A" "A" "A" "A" "A"
[3,] "A" "A" "A" "B" "A"
[4,] "B" "B" "B" "A" "A"
[5,] "A" "A" "B" "A" "A"