Home > Mobile >  Initialise a dataframe where a column references another column
Initialise a dataframe where a column references another column

Time:04-27

I wonder if there is a way to do:

df <- data.frame(x = 1:3)
df$y = df$x   5

yielding:

  x y
1 1 6
2 2 7
3 3 8

in one line of code where the y column refers to the x column? For example:

data.frame(x = 1:3, y = self$x   5)    # doesn't work

(I won't accept answers that ignore the x column, for example, data.frame(x = 1:3, y = 6:8 :-))

CodePudding user response:

This is possible using tibble from tibble library. Credit to @DaveArmstrong from the comments.

library(tibble)
tibble(x = 1:3, y = x   5)
# A tibble: 3 × 2
      x     y
  <int> <dbl>
1     1     6
2     2     7
3     3     8

CodePudding user response:

Here's a base R method that do not need to use external package (e.g. tibble).

We can use outer to add 5 to each element in df$x, then cbind the result with df.

setNames(data.frame(cbind(1:3, outer(1:3, 5, ` `))), c("x", "y"))

# or to expand your code
setNames(cbind(data.frame(x = 1:3), outer(1:3, 5, ` `)), c("x", "y"))

  x y
1 1 6
2 2 7
3 3 8
  •  Tags:  
  • r
  • Related