dplyr operations for single row

Asked by At

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 being 2 for all rows.

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

2 Answers

0
Roman On Best Solutions

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))
1
surpavan On

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