r - 获取合并到 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
该函数将采用上述内容并吐出tibble
45 长: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
解决方案
你可以试试 -
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
推荐阅读
- python - 如何解决数据集数量少且两个类之间的特征相似/易混淆的分类问题
- python - 使用 imap_tools(或 imaplib),如何通过重复获取整个 imap 数据库来同步 imap 更改而不是轮询?
- javascript - 将每个函数应用于 forEach javascript
- php - 空字符串与零的比较在 PHP 8 中给出了与以前版本不同的结果
- c++ - cpp中的crypto++ aes GCM-AEAD解密抛出异常哈希或MAC无效'
- ruby-on-rails - 尝试在主页上显示照片时出错:“资产管道中不存在资产“课程/图像1””
- node.js - Heroku - 在健康检查失败时重新启动
- javascript - Selenium 定位器:无效的元素状态
- java - 为什么我通过从 bean 调用 @Stateless 方法得到 TransactionRequiredException?
- amazon-web-services - 有没有办法在触发 lambdas 之前过滤 AWS DynamoDb 流?