首页 > 解决方案 > 获取合并到 tibble 中的向量的第 i_th 值

问题描述

我有一个tibble我想添加一列的。tibble可以是任意长度 n,其中它是三个变量的结果:

x <- 1:5 # can be any sequence length
u <- 3L # can be any integer
data_length <- length(x)
h <- 3L # can be any integer

该函数将采用上述内容并吐出tibble45 长:data_length * u * h

现在我还有一个nt由 制作的向量,nt <- seq(from = 1, to = length(x) + 1 - 1/u, by = 1/u)在这种情况下将给出以下内容:

[1] 1.000000 1.333333 1.666667 2.000000 2.333333 2.666667 3.000000 3.333333 3.666667 4.000000
[11] 4.333333 4.666667 5.000000 5.333333 5.666667

我希望能够做到tibble以下几点:

nt  | x | h 
-----------
1   | 1 | 1
1.3 | 0 | 1
1.6 | 0 | 1
2   | 2 | 1
2.3 | 0 | 1
... |...|...
5   | 5 | 1
... |...|...
1   | 1 | 3
1.3 | 0 | 3
1.6 | 0 | 3

标签: rdplyr

解决方案


你可以试试 -

library(dplyr)

replicate(h, tibble(nt) %>%
  mutate(x = replace(nt, -seq(1, n(), u), 0)), simplify = FALSE) %>%
  bind_rows(.id = 'h')

# A tibble: 45 x 3
#    h         nt     x
#   <chr>  <dbl> <dbl>
# 1 1     1          1
# 2 1     1.3333     0
# 3 1     1.6667     0
# 4 1     2          2
# 5 1     2.3333     0
# 6 1     2.6667     0
# 7 1     3          3
# 8 1     3.3333     0
# 9 1     3.6667     0
#10 1     4          4
# … with 35 more rows

推荐阅读