变异后使用~分离,交叉使用 [英] Use ~separate after mutate and across
本文介绍了变异后使用~分离,交叉使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
目标是将所有物种&setosa&q;行转换为一行:(这是一个最小的示例(在实际的多列多组中):
我有此数据帧:
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
我使用summarise
和toString
获取:
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"
我想学习如何在mutate
和across
之后应用separate
函数。
推荐答案
主要问题是separate
需要以data.Frame形式输入。如果我们希望在across
中执行separate
,则可以将tibble
包装在tibble
中,然后执行separate
,最后在list
输出中执行unnest
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
这篇关于变异后使用~分离,交叉使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文