[英]R - Given a List of Vectors replace values in Vectors for each Vector with LOOP
[英]R count values of a vector in ranges given by two other vectors
R:假設
length(v)=n length(a)=m=length(b),
n and m are large;
v, a, b may contain NA or NaN's;
a not necessarily smaller than b.
如何找到這樣的索引對ij的數量
a[j] < v[i] < b[j]
如何找到其中一個的(i,j)數
a[j] < v[i] < b[j] or a[j] > v[i] > b[j]
這似乎太慢了:
sumrange <- function(v,ma)
{
s <- 0
for(i in 1:length(v))
{
s <- s + sum(v[i] > ma[,1] & ma[,2] > v[i], na.rm = TRUE)
}
s
}
result <- sumrange(v, cbind(a, b))
編輯:@DatamineR
a<-c(1,6,4,2,NA)
b<-c(5,4,0,7,0)
v<-c(3,5)
問題1的可能對:
1<3<5 (1,1)
2<3<7 (1,4)
2<5<7 (2,4)
結果= 3
問題2的可能對:以上所有和
6> 5> 4(2,2)
結果= 3 + 1 = 4
編輯:實際上它的效果更好,是先丟下NA
vc<-na.omit(v)
ma<-na.omit(cbind(a,b))
result<-sumrange(vc,ma)
也許是這樣嗎?
# some data:
set.seed(123)
a <- sample(1:15, 10)
b <- sample(1:15, 11)
c <- sample(1:15, 10)
a;b;c
[1] 5 12 6 11 14 1 15 8 4 3
[1] 15 7 9 14 2 13 3 1 10 6 5
[1] 11 9 13 8 12 6 10 3 2 14
res <- sapply(b, function(x) apply(cbind(a,c), 1, function(y) (y[1] < x) & (x < y[2])))
which(res, arr.ind = TRUE)
row col
[1,] 1 2
[2,] 3 2
[3,] 10 2
[4,] 1 3
[5,] 3 3
[6,] 10 3
[7,] 6 5
[8,] 10 6
[9,] 6 7
[10,] 1 9
[11,] 3 9
[12,] 10 9
[13,] 1 10
[14,] 10 10
[15,] 6 11
[16,] 10 11
在此,第一列是j
,第二列是i
。
包括兩個條件:
res2 <- sapply(b, function(x) apply(cbind(a,c), 1, function(y) ((y[1] < x) & (x < y[2])) | ((y[1] > x) & (x > y[2])) ))
which(res2, arr.ind = TRUE)
row col
[1,] 1 2
[2,] 3 2
[3,] 8 2
[4,] 10 2
[5,] 1 3
[6,] 3 3
[7,] 4 3
[8,] 10 3
[9,] 7 4
[10,] 6 5
[11,] 5 6
[12,] 7 6
[13,] 10 6
[14,] 6 7
[15,] 9 7
[16,] 1 9
[17,] 2 9
[18,] 3 9
[19,] 4 9
[20,] 10 9
[21,] 1 10
[22,] 8 10
[23,] 10 10
[24,] 6 11
[25,] 8 11
[26,] 10 11
我發現使用帶狀皰疹的方法稍快一些,如果事先去除NA的話效果最好
require(lattice)
vc<-na.omit(v)
ma<-na.omit(cbind(a,b))
sh<-shingle(vc,ma)
res<-sapply(levels(sh), function(x) sum(x[1] < vc & vc <= x[2]))
result<-sum(res)
m = 1000(通過na.omit減少為912)和n = 2000的時序,而使用for循環(和函數)的0.28和使用for循環的0.38的時序在應用之前不清除數據。
但是,如果有多個條件,我仍然不知道如何使用帶狀皰疹:假設v是一個2乘矩陣,而a和b是2乘以m矩陣,我們要計算有多少對(i,j)這樣
(a[j,1]<v[i,1]<b[j,1]) & (a[j,2]<v[i,2]<b[j,2])
那是當(多維)點位於(多維)矩形中時
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.