I am struggling with a theoretically simple problem with R:
我正在努力解决R的一个理论上简单的问题:
say I have the following matrix:
说我有以下矩阵:
a <- matrix(1:16,ncol=4)
and the following vector showing the column position I need to extract for each row:
以下向量显示我需要为每行提取的列位置:
b <- c(4,3,1,1)
I need to return the following vector:
我需要返回以下向量:
[1] 13 10 3 4
In other words, for each row I need to extract the element whose column position is shown in the corrisponding c value.
换句话说,对于每一行,我需要提取其列位置显示在相应c值中的元素。
I have search extensively on this site but could not find a solution.
我在这个网站上广泛搜索但找不到解决方案。
Can anyone please help me? Thanks
谁能帮帮我吗?谢谢
1 个解决方案
#1
1
You can try
你可以试试
a[cbind(1:nrow(a), b)]
#[1] 13 10 3 4
#1
1
You can try
你可以试试
a[cbind(1:nrow(a), b)]
#[1] 13 10 3 4