独特载体的指数

时间:2013-04-22 23:30:07

标签: r vector indexing

我在R中有2个向量。我可以生成由其唯一元素组成的向量,但我需要知道向量a的每个元素的索引,例如:

 x <- c(0, 0, 2, 4, 8)
 y <- c(1, 4, 6, 6, Inf)
 a <- unique(sort(c(x, y)))

 > a
 [1]   0   1   2   4   6   8 Inf

我需要证明0a)中的索引为x1x21的索引为{{1} } {} y12x34x4等。

我如何在R?

中执行此操作

3 个答案:

答案 0 :(得分:5)

sapply(unique(x), function(z) which(x==z)  )

这是非常基本的东西,你真的应该学习R的介绍并在你的控制台上运行这些例子。

答案 1 :(得分:1)

我猜你想要一个函数,应用于a,它将返回找到每个元素的向量的名称以及该向量中的位置。

这不是很漂亮,但应该做你想做的事:

fun1 <- function(i) {
        res <- NULL
        if (a[i] %in% x) res <- paste("x",which(x==a[i]),sep="")
        if (a[i] %in% y) res <- c(res, paste(" y",which(y==a[i]),sep=""))
        names(res) <- rep(a[i],length(res))
        return(res)
        }

然后

unlist(sapply(1:length(a), FUN = fun1))

给出

    0     0     1     2     2     4     6     6     8   Inf 
 "x1"  "x2" " y1"  "x3" " y2"  "x4" " y3" " y4"  "x5" " y5"

更新这就是您要找的内容吗?

fun1 <- function(i) {
    res1 <- res2 <- NULL
    if (a[i] %in% x) res1 <- paste("x", which(x %in% a[i]),sep="",collapse=" ")            
    if (a[i] %in% y) res2 <- paste("y", which(y %in% a[i]),sep="",collapse=" ")
    res <- paste(res1,res2,collapse="")
    names(res) <- a[i]
    ascii:::trim(res)
    }

,与之前的用法相同,给出了

      0       1       2       4       6       8     Inf 
"x1 x2"    "y1" "x3 y2"    "x4" "y3 y4"    "x5"    "y5" 

答案 2 :(得分:1)

为什么不命名原始矢量,然后使用tapply来获得你想要的东西

names(x) <- paste0('x', seq_along(x))
names(y) <- paste0('y', seq_along(y))

# combine and sort
xy <- sort(c(x,y))
xy
## x1  x2  y1  x3  x4  y2  y3  y4  x5  y5 
##  0   0   1   2   4   4   6   6   8 Inf 

tapply(names(xy), xy, list)

# $`0`
# [1] "x1" "x2"
# 
# $`1`
# [1] "y1"
# 
# $`2`
# [1] "x3"
# 
# $`4`
# [1] "x4" "y2"
# 
# $`6`
# [1] "y3" "y4"
# 
# $`8`
# [1] "x5"
# 
# $`Inf`
# [1] "y5"
相关问题