gpt4 book ai didi

r - 如何在 R 中创建具有特定间隔的向量?

转载 作者:行者123 更新时间:2023-12-03 07:47:55 26 4
gpt4 key购买 nike

我有一个关于创建向量的问题。如果我这样做a <- 1:10 ,“a”的值为 1,2,3,4,5,6,7,8,9,10。

我的问题是如何创建一个元素之间具有特定间隔的向量。例如,我想创建一个具有从 1 到 100 的值的向量,但仅以 5 为间隔进行计数,这样我就得到一个具有值 5,10,15,20,...,95,100 的向量

我认为在Matlab中我们可以做到1:5:100 ,我们如何使用 R 来做到这一点?

我可以尝试做5*(1:20)但有没有更短的方法呢? (因为在这种情况下,我需要知道整个长度 (100),然后除以间隔的大小 (5) 以获得 20)

最佳答案

在 R 中,等效函数是 seq,您可以将其与选项 by 一起使用:

seq(from = 5, to = 100, by = 5)
# [1] 5 10 15 20 25 30 35 40 45 50 55 60 65 70 75 80 85 90 95 100
<小时/>

除了by之外,您还可以有其他选项,例如length.outalong.with

length.out:如果要获取0到1之间总共10个数字,例如:

seq(0, 1, length.out = 10)
# gives 10 equally spaced numbers from 0 to 1

along.with:它将您提供的向量的长度作为输入,并提供来自 1:length(input) 的向量。

seq(along.with=c(10,20,30))
# [1] 1 2 3

不过,在这种情况下,建议使用 seq_along,而不是使用 along.with 选项。来自 ?seq

的文档

seq is generic, and only the default method is described here. Note that it dispatches on the class of the first argument irrespective of argument names. This can have unintended consequences if it is called with just one argument intending this to be taken as along.with: it is much better to use seq_along in that case.

seq_along:而不是seq(along.with(.))

seq_along(c(10,20,30))
# [1] 1 2 3

关于r - 如何在 R 中创建具有特定间隔的向量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15601609/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com