目的是將所有物種“setosa”行轉換為一行“setosa”:(這是一個最小的例子(實際上更多的列和更多的組):
我有這個資料框:
head(iris, 2) %>%
select(1,2,5) %>%
group_by(Species)
Sepal.Length Sepal.Width Species
<dbl> <dbl> <fct>
1 5.1 3.5 setosa
2 4.9 3 setosa
我使用summarisewithtoString來獲取:
Species Sepal.Length Sepal.Width
<fct> <chr> <chr>
1 setosa 5.1, 4.9 3.5, 3
預期輸出:我想要這個資料框:
Species Sepal.Length1 Sepal.Length2 Sepal.Width1 Sepal.Width2
<fct> <dbl> <dbl> <dbl> <int>
1 setosa 5.1 4.9 3.5 3
我用這個作業代碼實作了這一點:
head(iris, 2) %>%
select(1,2,5) %>%
group_by(Species) %>%
summarise(across(everything(), ~toString(.))) %>%
ungroup() %>%
separate(Sepal.Length, c("Sepal.Length1", "Sepal.Length2"), sep = ", ", convert = TRUE) %>%
separate(Sepal.Width, c("Sepal.Width1", "Sepal.Width2"), sep = ", ", convert = TRUE)
但是我希望能夠separate在mutate across匿名函式后使用這個不起作用的代碼:
head(iris, 2) %>%
select(1,2,5) %>%
group_by(Species) %>%
summarise(across(everything(), ~toString(.))) %>%
ungroup() %>%
mutate(across(-1, ~separate(., into = paste0(., 1:2), sep = ", ", convert = TRUE)))
Error: Problem with `mutate()` input `..1`.
i `..1 = across(-1, ~separate(., into = paste0(., 1:2), sep = ", ", convert = TRUE))`.
x no applicable method for 'separate' applied to an object of class "character"
我想學習如何separate在mutate和之后應用函式across。
uj5u.com熱心網友回復:
另一種方法,長軸旋轉,轉換,然后再次寬軸旋轉。
library(tidyverse)
head(iris, 2) %>%
select(1,2,5) %>%
pivot_longer(-Species) %>%
group_by(name) %>% mutate(col = paste0(name, row_number())) %>% ungroup() %>%
select(-name) %>%
arrange(col) %>% # for ordering columns like OP
pivot_wider(names_from = col, values_from = value)
# A tibble: 1 x 5
Species Sepal.Length1 Sepal.Length2 Sepal.Width1 Sepal.Width2
<fct> <dbl> <dbl> <dbl> <dbl>
1 setosa 5.1 4.9 3.5 3
uj5u.com熱心網友回復:
主要問題是separate需要輸入為 data.frame。我們可以包裝在 a 中tibble,然后separate如果我們想要這個across,最后unnest是list輸出
library(dplyr)
library(tidyr)
library(stringr)
head(iris, 2) %>%
select(1,2,5) %>%
group_by(Species) %>%
summarise(across(everything(), ~toString(.)), .groups = 'drop') %>%
mutate(across(-1, ~ list(tibble(col1 = .) %>%
separate(col1, into = str_c(cur_column(), 1:2), sep = ",\\s ")))) %>%
unnest(cols = c(Sepal.Length, Sepal.Width))
-輸出
# A tibble: 1 × 5
Species Sepal.Length1 Sepal.Length2 Sepal.Width1 Sepal.Width2
<fct> <chr> <chr> <chr> <chr>
1 setosa 5.1 4.9 3.5 3
uj5u.com熱心網友回復:
另一種解決方案:
library(tidyverse)
head(iris, 2) %>%
select(1,2,5) %>%
group_by(Species) %>%
summarise(across(everything(), ~toString(.))) %>%
separate(2, into = paste0("Sepal.Length",1:2), sep=", ") %>%
separate(4, into = paste0("Sepal.Width",1:2), sep=", ")
#> # A tibble: 1 × 5
#> Species Sepal.Length1 Sepal.Length2 Sepal.Width1 Sepal.Width2
#> <fct> <chr> <chr> <chr> <chr>
#> 1 setosa 5.1 4.9 3.5 3
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/342975.html
上一篇:pivot_longer:values_ptypes:不能將<integer>轉換為<character>
下一篇:按組劃分的dplyr中位數
