简体   繁体   中英

How does one stop using rowwise in dplyr?

So, if one wishes to apply an operation row by row in dplyr, one can use the rowwise<\/code> function, for example: Applying a function to every row of a table using dplyr?<\/a>

Currently, it seems adding a group_by<\/code> after the rowwise<\/code> removes row operations, eg

data.frame(a=1:4) %>% rowwise() %>% group_by(a)
# ...
# Warning message:
# Grouping rowwise data frame strips rowwise nature 

As found in the comments and the other answer, the correct way of doing this is to use ungroup() .

The operation rowwise(df) sets one of the classes of df to be rowwise_df . We can see the methods on this class by examining the code here , which gives the following ungroup method:

#' @export
ungroup.rowwise_df <- function(x) {
  class(x) <- c( "tbl_df", "data.frame")
  x
}

So we see that ungroup is not strictly removing a grouped structure, instead it just removes the rowwise_df class added from the rowwise function.

Just use ungroup()

The following produces a warning:

data.frame(a=1:4) %>% rowwise() %>% 
  group_by(a)
#Warning message:
#Grouping rowwise data frame strips rowwise nature

This does not produce the warning:

data.frame(a=1:4) %>% rowwise() %>% 
  ungroup() %>% 
  group_by(a)

You can use as.data.frame()<\/code> , like below

> data.frame(a=1:4) %>% rowwise() %>% group_by(a)
# A tibble: 4 x 1
# Groups:   a [4]
      a
* <int>
1     1
2     2
3     3
4     4
Warning message:
Grouping rowwise data frame strips rowwise nature 

> data.frame(a=1:4) %>% rowwise() %>% as.data.frame() %>% group_by(a)
# A tibble: 4 x 1
# Groups:   a [4]
      a
* <int>
1     1
2     2
3     3
4     4

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM