【问题标题】:R - tidyverse approach to split a dataframe by columns and keep a set of common columnsR - 按列拆分数据框并保留一组公共列的 tidyverse 方法
【发布时间】:2022-12-09 15:36:02
【问题描述】:

我的问题与this one 非常相似,但我更愿意采用 tidyverse 方法。

我有一个包含多个列的数据集,我想按列拆分它(不是按行!),但在每个数据集中保留一个公共列列表。为了说明这一点,我将使用 iris 数据集,假设 Species 是我要保留的公共列。

仅使用这些简单的操作就可以很容易地做到这一点:

iris1 <- iris[,c("Species", "Sepal.Width")]
iris2 <- iris[,c("Species", "Sepal.Length")]
iris3 <- iris[,c("Species", "Petal.Width")]
iris4 <- iris[,c("Species", "Petal.Length")]

所以我想实现与此相同的输出,但采用 tidyverse 风格并且可在管道中使用而不会破坏它。

【问题讨论】:

    标签: r


    【解决方案1】:

    要以 tidyverse 样式执行此操作,您可以使用 dplyr 包中的 select() 函数对 iris 数据集中的列进行子集化。例如,您可以执行以下操作:

    # Load the dplyr package
    library(dplyr)
    
    # Subset the iris dataset to keep only the Species and Sepal.Width columns
    iris1 <- iris %>% select(Species, Sepal.Width)
    
    

    【讨论】:

    • 感谢您的尝试,但使用您的方法无法在一个管道中完成所有 4 件事。您将不得不中断管道并进行 4 次不同的操作
    猜你喜欢
    • 2023-02-21
    • 1970-01-01
    • 1970-01-01
    • 2016-06-27
    • 2021-03-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多