r - Find the indices of top n elements in a row after ignoring selected indices -
i have dataframe df1
, list l1
:
df1 <- data.frame(c1 = c(4.2, 1.2, 3.0) , c2 = c(2.3, 1.8, 12.0 ) ,c3 = c(1.2, 3.2, 2.0 ) , c4 = c(2.2, 1.9, 0.9) ) l1 <- list(x1 = c(2,4) ,x2 = c(3) ,x3 = c(2))
where l1 contains list of indices ignore in df1. now, want find indices of top 2 (can higher) elements after excluding indices in list l1 every row. actual data has more rows , columns. so, expected output :
[1,] 1 3 [2,] 2 4 [3,] 1 3
where df1 :
c1 c2 c3 c4 1 4.2 2.3 1.2 2.2 2 1.2 1.8 3.2 1.9 3 3.0 12.0 2.0 0.9
if indices can in order of values of placeholders, helpful. expected output :
[1,] 1 3 [2,] 4 2 [3,] 1 3
we can use rank
lapply(seq_len(nrow(df1)), function(i) { x1 <- unlist(df1[i,]) i2 <- l1[[i]] i3 <- seq_along(x1) %in% i2 which(rank(-x1*na^i3) %in% 1:2) }) #[[1]] #[1] 1 3 #[[2]] #[1] 2 4 #[[3]] #[1] 1 3
update
if need in order
lapply(seq_len(nrow(df1)), function(i) { x1 <- unlist(df1[i,]) i2 <- l1[[i]] i3 <- seq_along(x1) %in% i2 i4 <- which(rank(-x1*na^i3) %in% 1:2) i4[order(-x1[i4])] }) #[[1]] #[1] 1 3 #[[2]] #[1] 4 2 #[[3]] #[1] 1 3
Comments
Post a Comment