我有一个矩阵,
set.seed(100)
x <- matrix(sample(11, 110, replace = T), nrow = 11)
和另一个矩阵,
y <- cbind(1:11, sample(110, 11))
我想将x
的每个元素与y
的第一列相匹配。如果匹配应返回y
其他0
的第二列。最终出局应与x
具有相同的维度。
我尝试使用带有3个嵌套循环的for-loop
执行此操作,但有没有有效的方法呢?
预期输出
[,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
[1,] 26 85 4 40 96 9 4 21 26 21
[2,] 9 26 21 75 4 88 103 85 21 26
[3,] 96 103 103 85 21 9 9 88 85 103
[4,] 93 21 88 88 85 96 75 4 9 93
[5,] 4 75 21 96 9 9 103 96 26 26
[6,] 4 9 85 40 26 4 26 40 103 96
[7,] 21 26 96 88 26 75 96 40 85 75
[8,] 103 26 26 26 9 40 40 93 103 40
[9,] 96 75 4 85 9 75 75 96 4 75
[10,] 88 4 40 21 26 103 96 21 88 93
[11,] 96 75 26 85 96 26 85 9 93 4
答案 0 :(得分:3)
这是一种可能性:
x[!x%in%y[,1]] <- 0 # set all elements to zero which are not in first column of y
sapply(1:nrow(y),function(i) x[x==y[i,1]] <<- y[i,2]) #replace all matches with second column of y
#> x
# [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
# [1,] 26 85 4 40 96 21 4 21 26 21
# [2,] 21 26 21 75 4 88 103 85 21 26
# [3,] 96 103 103 85 21 21 21 88 85 103
# [4,] 93 21 88 88 85 96 75 4 21 93
# [5,] 4 75 21 96 21 21 103 96 26 26
# [6,] 4 21 85 40 26 4 26 40 103 96
# [7,] 21 26 96 88 26 75 96 40 85 75
# [8,] 103 26 26 26 21 40 40 93 103 40
# [9,] 96 75 4 85 21 75 75 96 4 75
#[10,] 88 4 40 21 26 103 96 21 88 93
#[11,] 96 75 26 85 96 26 85 21 93 4
答案 1 :(得分:0)
使用@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
getWindow().requestFeature(Window.FEATURE_CONTENT_TRANSITIONS);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_detail_folder_view);
setUpWindowAnimation();
@TargetApi(21)
private void setUpWindowAnimation() {
Explode explode = new Explode();
explode.setDuration(1000);
getWindow().setEnterTransition(explode);
getWindow().setExitTransition(explode);
getWindow().setReenterTransition(explode);
}
:
replace