Quantcast
Channel: Active questions tagged r - Stack Overflow
Viewing all articles
Browse latest Browse all 205372

Operations on single row in dplyr [duplicate]

$
0
0

This question already has an answer here:

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.


Viewing all articles
Browse latest Browse all 205372

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>