R:基于列表创建矢量

时间:2017-09-12 20:57:02

标签: r

我有以下名为m1的列表:

> m1
[[1]]
[1] 36 37 38

[[2]]
[1] 34 35

[[3]]
[1] 30 31 32 33

[[4]]
[1] 24 25 26 27 28 29

[[5]]
[1] 20 21 22 23

[[6]]
[1] 14 15 16 17 18 19

[[7]]
[1] 11 12 13

[[8]]
[1]  7  8  9 10

[[9]]
[1] 5 6

[[10]]
[1] 1 2 3 4

[[11]]
integer(0)

我想基于这个列表创建一个向量,它在位置36,37和38处的值为1;位置34和35处的值2等。最终输出应为:

vector_1 <- c(10, 10, 10, 10, 9, 9, 8, 8, 8, 8, 7, 7, 7, 6, 6, 6, 6, 6, 6, 5, 5, 5, 5, 4, 4, 4, 4, 4, 4, 3, 3, 3, 3, 2, 2, 1, 1, 1)

我如何在R?

中完成此任务

编辑:

感谢下面的评论:

> rep(length(m1):1, sapply(m1, length))
 [1] 11 11 11 10 10  9  9  9  9  8  8  8  8  8  8  7  7  7  7  6  6  6  6  6  6  5  5  5  4
[30]  4  4  4  3  3  2  2  2  2

这并没有给我我想要的东西,但它绝对是在正确的轨道上!

4 个答案:

答案 0 :(得分:3)

这应该处理具有空条目和非顺序条目的案例....

m1 <- list(c(7,4,5), c(2,10,9), c(1,3,6,8), integer())
# [[1]]
# [1] 7 4 5
# 
# [[2]]
# [1]  2 10  9
# 
# [[3]]
# [1] 1 3 6 8
# 
# [[4]]
# integer(0)

rep(seq_along(m1), sapply(m1, length))[order(unlist(m1))]
#[1] 3 2 3 1 1 3 1 3 2 2

答案 1 :(得分:2)

即使m1内的元素不符合特定顺序,此解决方案也适用于更一般的情况

#DATA
m1 = list(36:38, 34:35, 30:33, 24:29, 20:23,
          14:19, 11:13, 7:10, 5:6, 1:4, integer(0))

#Extract the maximum element in m1
mymax = max(unlist(m1))
#Go through m1 using index and replace respective indices in the position
#defined by the elements of m1, otherwise make the elements zero 
Reduce("+", lapply(1:length(m1), function(i)
    replace(rep(0, mymax), m1[[i]], i)))
# [1] 10 10 10 10  9  9  8  8  8  8  7  7  7  6  6  6  6  6  6  5  5  5  5
#[24]  4  4  4  4  4  4  3  3  3  3  2  2  1  1  1

答案 2 :(得分:2)

这是一个简单的基础R解决方案:

# data
m1 <- list(36:38, 34:35, 30:33, 24:29, 20:23, 14:19, 11:13, 7:10, 5:6, 1:4, integer(0))

# Count length, and repeat each number in 1:11 accordingly
rev(rep(1:11, sapply(m1, length)))
 [1] 10 10 10 10  9  9  8  8  8  8  7  7  7  6  6  6  6  6  6  5  5  5  5  4  4  4  4  4  4  3  3  3
[33]  3  2  2  1  1  1

修改: 一个更普遍的答案是:

rev(rep(seq_along(m1), sapply(m1, length)))

答案 3 :(得分:1)

试试这个:

rev(unlist(sapply(1:length(m1), function(x) rep(x,length(m1[[x]])))))

#or even better, @snoram's edited version of this:

rev(rep(seq_along(m1), sapply(m1, length)))

输出:

[1] 10 10 10 10  9  9  8  8  8  8  7  7  7  6  6  6  6  6  6  5  5  5  5  4
[25]  4  4  4  4  4  3  3  3  3  2  2  1  1  1

示例数据:

m1 <- list(36:38,34:35,30:33,24:29,20:23,
           14:19,11:13,7:10,5:6,1:4)
names(m1) <- 1:10