How does one stop using rowwise in dplyr?
RDplyrR Problem Overview
So, if one wishes to apply an operation row by row in dplyr, one can use the rowwise
function, for example: https://stackoverflow.com/questions/21818181/applying-a-function-to-every-row-of-a-table-using-dplyr/24728107#24728107
Is there a unrowwise
function which you can use to stop doing operations row by row? Currently, it seems adding a group_by
after the rowwise
removes row operations, e.g.
data.frame(a=1:4) %>% rowwise() %>% group_by(a)
# ...
# Warning message:
# Grouping rowwise data frame strips rowwise nature
Does this mean one should use group_by(1)
if you wish to explicitly remove rowwise
?
R Solutions
Solution 1 - R
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][1], 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.
[1]: http://ungroup.rowwise_df%20%3C-%20function(x)%20%7B%20%20%20class(x)%20%3C-%20c( "tbl_dfquot;, quot;data.framequot;) x } quot;"
Solution 2 - R
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)
Solution 3 - R
You can use as.data.frame()
, 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