简体   繁体   English

找出给定数字在R中的向量序列中的位置

[英]Find out where the given numbers are located in the series of vector in R

I have three variables a1, a2 and a3. 我有三个变量a1,a2和a3。

a1 <- 1:10
a2 <- 11:20
a3 <- 21:30

then I have another variable called my.numbers <- c(1, 20, 22,11) 然后我有另一个变量my.numbers <- c(1, 20, 22,11)

I want to find out where these numbers are located. 我想找出这些数字的位置。 So the result I want is: 所以我想要的结果是:

1 in a1
20 in a2
22 in a3
11 in a2

Any suggestion on how it can be done easy way? 关于如何可以轻松完成的任何建议?

For the record here is how you can get out the exact result in the question. 作为记录,这里是您如何找出问题的确切结果。

a1 <- 1:10
a2 <- 11:20
a3 <- 21:30

L<-list("a1"=a1,"a2"=a2,"a3"=a3)
my.numbers <- c(1, 20, 22, 11)

func<-function(item){
    my.numbers[which(my.numbers %in% item)]
}

Fin<-lapply(L, func)

for(i in 1:length(Fin)){
Index<-unlist(Fin[i])
name<-paste("a",i, sep="")
    for(i in 1:length(Index)){
       print(paste(Index[i], "in", name))
    }
}

[1] "1 in a1"
[1] "20 in a2"
[1] "11 in a2"
[1] "22 in a3"

With a couple purrr::map functions, you can work across the numbers, then within that, across the a vectors. 一对夫妇purrr::map功能,您可以在数字工作,那么内,整个a载体。

I'm making a list of the a vectors with tibble::lst because it sets the names of the list as the names of the variables going into it—convenient for something like this where it's the name of the list item that's important. 我用tibble::lst制作了a矢量列表,因为它将列表的名称设置为要进入其中的变量的名称-像这样的事情很方便,因为重要的是列表项的名称。

library(tidyverse)

a_list <- lst(a1, a2, a3)

my.numbers %>%
  map_chr(function(num) {
    which_a <- map_lgl(a_list, ~(num %in% .))
    a_name <- names(a_list)[which_a]
    str_glue("{num} in {a_name}")
  })
#> [1] "1 in a1"  "20 in a2" "22 in a3" "11 in a2"

You could use match or another function after the map_lgl instead—I left it verbose to make it a little more clear what's going on. 您可以在map_lgl之后使用match或其他函数-我将其保留为冗长的名称,以使情况更加清楚。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM