r - R中的双重拆分数据集
问题描述
有没有办法将数据集拆分为其原始组件的排列?例如,我刚才意识到 split() 将数据集(和选择的列)拆分为列的每个元素的迷你数据集,但是如果我有一个数据集“冠军”,其中列“问题”和元素
a, b, c
和带有元素的“年”
2018, 2019
(在其他列中)并且我想为“冠军”中的所有观察结果创建迷你数据集,其中“问题”= 1,年份=“2018”以及其他列中的任何元素,我该怎么做?
编辑:此外,我正在使用的列的元素比这些示例多得多,那么我将如何为每个列创建新对象?
我的预期结果基本上是我想象的如果我将 filter() 函数应用于“问题”的每个元素,然后应用于“年份”的每个元素,然后为这些输出中的每一个创建对象,会发生什么。
数据集:
structure(list(id = structure(c(25, 25, 25, 25, 25, 25, 25, 25,
25, 25), format.stata = "%8.0g"), year = structure(c(2018, 2018,
2018, 2018, 2018, 2018, 2018, 2018, 2018, 2018), format.stata = "%8.0g"),
round = structure(c(1, 1, 1, 1, 1, 1, 1, 1, 1, 1), format.stata = "%8.0g"),
question = structure(c(1, 2, 3, 4, 5, 6, 7, 8, 9, 10), format.stata = "%8.0g"),
correct = structure(c(0, 0, 0, 0, 0, 0, 1, 0, 1, 0), format.stata = "%8.0g")), row.names = c(NA,
-10L), class = c("tbl_df", "tbl", "data.frame"))
解决方案
question
您可以为每个和拆分数据集,year
根据选择分配名称并用于list2env
在全局环境中创建单个数据集。
data <- split(df, list(df$question, df$year))
names(data) <- sub('(\\d+)\\.(\\d+)', 'question\\1_year\\2', names(data))
names(data)
# [1] "question1_year2018" "question2_year2018" "question3_year2018"
# [4] "question4_year2018" "question5_year2018" "question6_year2018"
# [7] "question7_year2018" "question8_year2018" "question9_year2018"
#[10] "question10_year2018"
list2env(data, .GlobalEnv)
question1_year2018
# A tibble: 1 x 5
# id year round question correct
# <dbl> <dbl> <dbl> <dbl> <dbl>
#1 25 2018 1 1 0
question2_year2018
# A tibble: 1 x 5
# id year round question correct
# <dbl> <dbl> <dbl> <dbl> <dbl>
#1 25 2018 1 2 0
在全球环境中创建多个数据集不是一个好习惯。您应该将它们保存在列表中,这样更容易管理它们。
推荐阅读
- c# - c#中的Http Async Post,Raspberry Pi,数据不发布
- maven - 如何将 SAP MTA(多目标应用程序)转换为 Maven 项目?
- qt - 为什么 Qt .pro 文件根据不同平台添加源不起作用?
- angular - Ionic - TypeError: __WEBPACK_IMPORTED_MODULE_1_rxjs_Observable__.Observable.of 不是 mac 上的函数
- mxnet - 如何在 MxNet 中以优化器状态恢复训练
- javascript - 如何使用同位素取消选择过滤器?
- pyspark - rdd 上的映射如何在 pyspark 中工作?
- php - 加载 PDF 文档时出错
- json - 如何在 angular6 中验证 YAML 文件
- .htaccess - 在所有文件夹上强制使用 HTTPS 和非 WWW,但有例外