2

Is it possible to performa dplyr operations with pipes for single rows of a dataframe? For example say I have the following a dataframe (call it df) and want to do some manipulations to the columns of that dataframe:

df <- df %>%
mutate(col1 = col1 + col2)

This code sets one column equal to the sum of that column and another. What if I want to do this, but only for a single row?

df[1,] <- df[1,] %>%
mutate(col1 = col1 + col2)

I realize this is an easy operation in base R, but I am super curious and would love to use dplyr operations and piping to make this happen. Is this possible or does it go against dplyr grammar?

Here's an example. Say I have a dataframe:

df = data.frame(a = rep(1, 100), b = rep(1,100))

The first example I showed:

df <- df %>%
mutate(a = a + b)

Would result in column a_xPlacexHolderxColumnaPlacexHolderx_ being 2 for all rows.

The second example would only result in the first row of column a_xPlacexHolderxColumnaPlacexHolderx_ being 2.

M--
  • 25,431
  • 8
  • 61
  • 93
ben890
  • 1,097
  • 5
  • 25
  • 56
  • 4
    Duplicate of [dplyr mutate/replace on a subset of rows](https://stackoverflow.com/questions/34096162/dplyr-mutate-replace-on-a-subset-of-rows) – M-- Apr 25 '19 at 15:10
  • 2
    FWIW, `data.table` does this nicely: `setDT(df)` to convert `df` to a data.table, then `df[1, a := a + b]` will update `a` to be `a + b` in the first row only. – Gregor Thomas Apr 25 '19 at 15:16

2 Answers2

1

mutate() is for creating columns.

You can do something like df[1,1] <- df[1,1] + df[1,2]

An Example:

enter image description here

surpavan
  • 1,372
  • 7
  • 34
  • 66
  • Gotcha, dplyr operations only apply to whole columns rather than single elements? – ben890 Apr 25 '19 at 15:09
  • Yes, mutate is for adding new columns by using a function like code (within braces). We can use matrix like model to edit single rows & coluimns – surpavan Apr 25 '19 at 15:11
0

You can mutate() and case_when() for conditional manipulation.

df %>%
    mutate(a = case_when(row_number(a) == 1 ~ a + b,
                         TRUE ~ a))

results in

# A tibble: 100 x 2
       a     b
   <dbl> <dbl>
 1     2     1
 2     1     1
 3     1     1
 4     1     1
 5     1     1
 6     1     1
 7     1     1
 8     1     1
 9     1     1
10     1     1
# … with 90 more rows

Data

library(tidyverse)
df <- tibble(a = rep(1, 100), b = rep(1,100))
Roman
  • 4,744
  • 2
  • 16
  • 58