-
Notifications
You must be signed in to change notification settings - Fork 2.1k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Unexpected/impractical behaviour of rowwise() in combination with mutate_all() #6890
Comments
I think this is a more elegant way to do what you want head(mtcars) |>
tibble::rownames_to_column() |>
tidyr::pivot_longer(-rowname) |>
dplyr::mutate(rank = rank(value), .by = rowname) |>
tidyr::pivot_wider(id_cols = rowname, names_from = name, values_from = rank)
#> # A tibble: 6 × 12
#> rowname mpg cyl disp hp drat wt qsec vs am gear carb
#> <chr> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
#> 1 Mazda RX4 9 7 11 10 4 3 8 1 2 5.5 5.5
#> 2 Mazda RX4 W… 9 7 11 10 4 3 8 1 2 5.5 5.5
#> 3 Datsun 710 9 6.5 11 10 5 4 8 2 2 6.5 2
#> 4 Hornet 4 Dr… 9 7 11 10 5 6 8 2.5 1 4 2.5
#> 5 Hornet Spor… 9 7 11 10 5 6 8 1.5 1.5 4 3
#> 6 Valiant 8 7 11 10 4 6 9 2.5 1 5 2.5 Created on 2023-11-03 with reprex v2.0.2 |
Thank you for your suggestion. Your code shows a more "tidyversy" way of achieving my expected result. However, I supplied both my example and the expected results primarily to show that |
I think you have misunderstood how library(dplyr, warn.conflicts = FALSE)
df <- data.frame(
x = c(1, 2),
y = c("a", "b")
)
df %>%
rowwise() %>%
mutate_all(function(x) {
cat("element:", x, "\n")
x
})
#> element: 1
#> element: 2
#> element: a
#> element: b
#> # A tibble: 2 × 2
#> # Rowwise:
#> x y
#> <dbl> <chr>
#> 1 1 a
#> 2 2 b Created on 2023-11-06 with reprex v2.0.2 |
Thank you for taking the time to explain. Indeed I misinterpreted |
When trying to apply a function using
mutate_all()
to each row of a data frame usingrowwise()
, it seems the function only considers individual values, rather than the complete row.Comparing column-wise with rowwise operations:
Would it be possible to obtain the expected result with
rowwise()
?The text was updated successfully, but these errors were encountered: