Yve
Yve

Reputation: 51

Create sequence without end point

I would like to create a sequence with as many numbers as columns I use.

I know the seq(from = 1, to = 100, by = 1) function, but I want something like:

seq(from = 1, to = *"UNTIL LAST COLUMN"*, by = 1)

The reason is that I want to do this with several data frames and do not want to repeatedly type in the number of columns that they have (because they differ).

Upvotes: 1

Views: 795

Answers (2)

ThomasIsCoding
ThomasIsCoding

Reputation: 101129

The solution by @Cettt covers almost everything you want. Besides, you can also use seq_along(df) to generate the sequence.

For example

> df <- data.frame(1:3,2:4,3:5)
> seq_along(df)
[1] 1 2 3

Upvotes: 2

Cettt
Cettt

Reputation: 11981

Well you can use ncol to determine the number of columns in your data.frame:

  • Either use seq(from = 1, to = ncol(df), by = 1)
  • Or even shorter 1:ncol(df)
  • Or faster: seq_len(ncol(df))
  • Or seq(df)

Upvotes: 3

Related Questions