I have a matrix and a vector like this:
Matrix<-cbind(c(3,3,5,1),c(2,5,2,1))
Vector<-c(2,3,3,3)
我希望用向量的值替换矩阵中大于等于对应向量值的元素,使得矩阵现在看起来像这样:
MatrixNew<-cbind(c(2,3,3,1),c(2,3,2,1))
什么逻辑可以实现这个?
你可能认为必须使用apply(Matrix, \(x) pmin(x, Vector))
,但实际上,你可以直接在Matrix
上使用pmin()
,因为它会循环使用Vector
以匹配长度。
pmin(Matrix, Vector)
#> [,1] [,2]
#> [1,] 2 2
#> [2,] 3 3
#> [3,] 3 2
#> [4,] 1 1
ifelse
。> ifelse(Matrix >= Vector, Vector, Matrix)
[,1] [,2]
[1,] 2 2
[2,] 3 3
[3,] 3 2
[4,] 1 1
使用dplyr::mutate
也可以实现这一功能。在需要选择变量子集的情况下非常有用。
library(dplyr)
dd = structure(list(V1 = c(3, 3, 5, 1), ` V2` = c(2, 5, 2, 1), Condition = c(2,
3, 3, 3)), class = "data.frame", row.names = c(NA, -4L))
dd %>% mutate(across(contains('V'), ~ifelse(.>=Condition, Condition,. )))
V1 V2 Condition
# 1 2 2 2
# 2 3 3 3
# 3 3 2 3
# 4 1 1 3