Search code examples
rpipe

Generate new variable using reference to cell within pipe


I am trying to add a new column to a dataframe, with values coming from a specific cell of the same df. I want to do this within a pipe, without referring explicitely to the original dataframe.

In the example below, I would like to replace df[2,3] with an implicit reference to the df in the pipe. I tried .[2,3] but it doesn't work.

df <- data.frame(
  A = c(1, 2, 3, 4),
  B = c(5, 6, 7, 8),
  C = c(9, 10, 11, 12)
)

df <- df |> 
  mutate(D = df[2,3])

Solution

  • You were close. Try:

    df <- data.frame(
      A = c(1, 2, 3, 4),
      B = c(5, 6, 7, 8),
      C = c(9, 10, 11, 12)
    )
    
    df <- df |> 
      mutate(D = paste(df[2,3]))
    
    df
      A B  C  D
    1 1 5  9 10
    2 2 6 10 10
    3 3 7 11 10
    4 4 8 12 10
    
    

    In case you do not want to usedf[2,3] we can use magrittr pipe in dplyr, for instance.

    library(dplyr)
    
    df <- df %>% 
      mutate(D = paste(.[2,3]))
    
    df
      A B  C  D
    1 1 5  9 10
    2 2 6 10 10
    3 3 7 11 10
    4 4 8 12 10