Skip to content

Using rowwise and mutate to create new variables #3890

Description

@nealpsmith

When reviewing some code, I noticed there seems to be an issue with using rowwise() with mutate() to create a new dataframe column.

# Create a dataframe with some values that are in 2 rows
df <- as.data.frame(matrix(c(2,3,4,5,20,6,1,7,2,3), nrow = 2, byrow = TRUE))

# Use Apply to generate the median of each row: This gives correct values
df$apply.median <- apply(x, 1, median)

# Use rowwise with mutate to get medians: This gives incorrect values
df %<>% rowwise() %>%
  dplyr::mutate(dplyr.median=median(V1:V5))

df
Source: local data frame [2 x 7]
Groups: <by row>

# A tibble: 2 x 7
     V1    V2    V3    V4    V5 apply.median dplyr.median
  <dbl> <dbl> <dbl> <dbl> <dbl>        <dbl>        <dbl>
1     2     3     4     5    20            4         11  
2     6     1     7     2     3            3          4.5

I've seen this issue not just with looking at medians, but also other basic functions. For example if I try to look at the length of V1:V5 in the same manner, this is the output:

# Look for the length of the vector that is being used for the median
df %<>% rowwise() %>%
  dplyr::mutate(length = length(V1:V5))

> df
Source: local data frame [2 x 8]
Groups: <by row>

# A tibble: 2 x 8
     V1    V2    V3    V4    V5 apply.median dplyr.median length
  <dbl> <dbl> <dbl> <dbl> <dbl>        <dbl>        <dbl>  <int>
1     2     3     4     5    20            4         11       19
2     6     1     7     2     3            3          4.5      4

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions