John J.
John J.

Reputation: 1716

How can I make a variable in a dataset containing a vector of all numbers between two other variables?

Here's an example dataframe.

x <- c(1,2,3)
y <- c(10,10,10)

d <- data.frame(x, y)

I want to generate a third variable (z) containing a vector of all values in x:y. For example, the first value of z should be c(1,2,3,4,5,6,7,8,9,10).

How can I do this? Trying d$z <- d$x:d$y just gives the error "numerical expression has 3 elements: only the first used."

Upvotes: 1

Views: 65

Answers (3)

s_baldur
s_baldur

Reputation: 33488

Also base R:

d$z <- lapply(1:nrow(d), function(i) with(d[i, ], x:y))

> str(d)
'data.frame':   3 obs. of  3 variables:
 $ x: num  1 2 3
 $ y: num  10 10 10
 $ z:List of 3
  ..$ : int  1 2 3 4 5 6 7 8 9 10
  ..$ : int  2 3 4 5 6 7 8 9 10
  ..$ : int  3 4 5 6 7 8 9 10

Upvotes: 1

JMenezes
JMenezes

Reputation: 1059

 mapply(":", x, y)

Same as RLave answer but without requiring extra packages.

Upvotes: 4

RLave
RLave

Reputation: 8364

With purrr package and the function map2:

purrr::map2(x,y, function(x,y) x:y)

# [[1]]
# [1]  1  2  3  4  5  6  7  8  9 10
# 
# [[2]]
# [1]  2  3  4  5  6  7  8  9 10
# 
# [[3]]
# [1]  3  4  5  6  7  8  9 10

Of course this needs to give a list because of the different lengths. Note that the same could be achieved with a simple loop.

Upvotes: 1

Related Questions