【问题标题】:How can I change the indices of an R vector?如何更改 R 向量的索引?
【发布时间】:2018-06-06 02:06:06
【问题描述】:

我想将不同随机向量的结果绘制成线条(像随机游走一样看待它们),这样它们中的每一个都按顺序跟随前一个。

为此,我希望第二个向量的索引从第一个向量的结束处开始。

例如

a <- cumsum(rnorm(10))
b <- cumsum(rnorm(10))
head(a)
[1] -0.03900184 -0.37913568 -0.42521156
head(b)
[1]  1.3861861 -0.2418804  1.1159065

两个向量都自然地从[1] 索引到[10]。所以如果我绘制它们,它们会重叠(左图),而我希望bx 轴(右图)中跟随a

plot(a, type = "l", xlim=c(0,20), ylim=c(-10,10), xlab="", ylab="", col=2)
lines(b, col=3)

b 附加到a 似乎是一种途径,但是当我对结果向量进行子集化时,我再次得到一个从零开始的向量...

【问题讨论】:

    标签: r vector indexing


    【解决方案1】:

    您可以在lines 函数中指定x 参数。

    set.seed(146)
    
    a <- cumsum(rnorm(10))
    b <- cumsum(rnorm(10))
    
    plot(a, type = "l", xlim=c(0,20), ylim=c(-10,10), xlab="", ylab="", col=2)
    lines(x = 10:19, y = b, col=3)
    

    【讨论】:

      【解决方案2】:

      我们可以用NAs 直到length(a) -1 创建一个新的b,然后添加a 的最后一个值,然后附加b,然后在lines 参数中使用这个new_b

      set.seed(1)
      
      a <- cumsum(rnorm(10))
      b <- cumsum(rnorm(10))
      
      new_b <- c(rep(NA, length(a)-1),a[length(a)], b)
      
      plot(a, type = "l", xlim=c(0,20), ylim=c(-10,10), xlab="", ylab="", col=2)
      lines(new_b, col=3)
      

      【讨论】:

        【解决方案3】:

        使用ggplot2 这样的东西怎么样?

        library(tidyverse);
        set.seed(2017);
        a <- cumsum(rnorm(10))
        b <- cumsum(rnorm(10))
        stack(data.frame(a, b)) %>%
            rowid_to_column("x") %>%
            ggplot(aes(x, values)) +
            geom_line(aes(colour = ind))
        

        【讨论】:

          【解决方案4】:

          如果数据点索引对您很重要,我假设您正在使用时间序列类型的数据。您应该考虑对对象创建和子集进行时间序列索引以进行所需的操作。这是一个例子

          foo <- ts(1:10, frequency = 1, start = 1)
          
          # Subset using time series indexing
          foo1 <- ts(foo[1:5], start = index(foo)[1], frequency = frequency(foo))
          foo6 <- ts(foo[6:10], start  = index(foo)[6], frequency = frequency(foo))
          
          # Combine using appropriate index    
          fooNew <- ts(c(foo1, foo6), start = start(foo1), frequency = frequency(foo1))
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 2013-12-16
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2018-04-20
            相关资源
            最近更新 更多