英文:
How to `reframe` all the columns in a dataframe?
问题
你想要将包含所有列表列的tibble重新构造,而无需指定所有列的名称。以下是一个示例。my_data包含所有列表列,我想使用reframe
将其转换为常规数据框。你可以通过指定所有列的名称来实现这一点。
library(dplyr)
my_data <- tibble(C1 = list(c(1,2,3,4)),
C2 = list(c(5,6,7,8)),
C3 = list(c(9,10,11,12)))
my_data %>%
rowwise() %>%
reframe(C1, C2, C3) #我想要的输出
要重新构造所有列,你可以尝试以下方式:
my_data %>%
rowwise() %>%
reframe(across(everything()))
这将重新构造所有列,无需指定列名。
英文:
Hello I would like to reframe all the columns in a tibble that contains all list columns without having to specify all the columns by name. Below contains an example. my_data is all list columns and I want to turn it into a regular dataframe using reframe
. I can do this by specifying all the names of the columns.
library(dplyr)
my_data <- tibble(C1 = list(c(1,2,3,4)),
C2 = list(c(5,6,7,8)),
C3 = list(c(9,10,11,12)))
my_data |>
rowwise() |>
reframe(C1, C2, C3) #The output I would like to get
#> # A tibble: 4 × 3
#> C1 C2 C3
#> <dbl> <dbl> <dbl>
#> 1 1 5 9
#> 2 2 6 10
#> 3 3 7 11
#> 4 4 8 12
my_data |>
rowwise() |>
reframe(everything()) #Would like to find a way to reframe all the columns
#> Error in `reframe()`:
#> ℹ In argument: `everything()`.
#> ℹ In row 1.
#> Caused by error:
#> ! `everything()` must be used within a *selecting* function.
#> ℹ See <https://tidyselect.r-lib.org/reference/faq-selection-context.html> for
#> details.
答案1
得分: 2
我猜你可以使用tidyverse中的unnest()函数来将列表列展开成一个常规数据框。你可以使用unnest()和everything()来展开所有列:
library(tidyverse)
my_data <- tibble(C1 = list(c(1,2,3,4)),
C2 = list(c(5,6,7,8)),
C3 = list(c(9,10,11,
<details>
<summary>英文:</summary>
I guess you can probably do this using unnest() from tidyverse to flatten the list columns into a regular dataframe. You can use unnest() with everything() to unnest all columns:
library(tidyverse)
my_data <- tibble(C1 = list(c(1,2,3,4)),
C2 = list(c(5,6,7,8)),
C3 = list(c(9,10,11,12)))
my_data %>%
unnest(everything())
This function will return a new dataframe where all the list columns have been unnested. You can use it on any dataframe with list columns without having to specify each column by name. The `unnest(everything())` line of code is unnesting all columns.
</details>
# 答案2
**得分**: 1
Instead of `dplyr::reframe`, you could use `tidyr::unnest_longer` like this:
``` r
library(tidyr)
my_data |>
tidyr::unnest_longer(everything())
#> # A tibble: 4 × 3
#> C1 C2 C3
#> <dbl> <dbl> <dbl>
#> 1 1 5 9
#> 2 2 6 10
#> 3 3 7 11
#> 4 4 8 12
英文:
Instead of dplyr::reframe
you could use tidyr::unnest_longer
like so:
library(tidyr)
my_data |>
tidyr::unnest_longer(everything())
#> # A tibble: 4 × 3
#> C1 C2 C3
#> <dbl> <dbl> <dbl>
#> 1 1 5 9
#> 2 2 6 10
#> 3 3 7 11
#> 4 4 8 12
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论