如何在 R 中创建具有特定间隔的向量? [英] How do you create vectors with specific intervals in R?

查看:33
本文介绍了如何在 R 中创建具有特定间隔的向量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个关于创建向量的问题.如果我执行 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)# 给出从 0 到 1 的 10 个等距数字

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

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

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

的文档<块引用>

seq 是通用的,这里只介绍默认的方法.请注意,无论参数名称如何,它都会在 first 参数的类上调度.如果只用一个参数调用它,这可能会产生意想不到的后果,并打算将其作为一起使用.在这种情况下,最好使用 seq_along.

seq_along: 代替 seq(along.with(.))

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

希望这会有所帮助.

I have a question about creating vectors. If I do a <- 1:10, "a" has the values 1,2,3,4,5,6,7,8,9,10.

My question is how do you create a vector with specific intervals between its elements. For example, I would like to create a vector that has the values from 1 to 100 but only count in intervals of 5 so that I get a vector that has the values 5,10,15,20,...,95,100

I think that in Matlab we can do 1:5:100, how do we do this using R?

I could try doing 5*(1:20) but is there a shorter way? (since in this case I would need to know the whole length (100) and then divide by the size of the interval (5) to get the 20)

解决方案

In R the equivalent function is seq and you can use it with the option 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


In addition to by you can also have other options such as length.out and along.with.

length.out: If you want to get a total of 10 numbers between 0 and 1, for example:

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

along.with: It takes the length of the vector you supply as input and provides a vector from 1:length(input).

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

Although, instead of using the along.with option, it is recommended to use seq_along in this case. From the documentation for ?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: Instead of seq(along.with(.))

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

Hope this helps.

这篇关于如何在 R 中创建具有特定间隔的向量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆