【问题标题】:Extract dataframe into multiple subsets based on indices根据索引将数据帧提取到多个子集中
【发布时间】:2018-12-15 00:11:14
【问题描述】:

我有一个包含大量列的数据框。我想根据开始索引和结束索引在列处拆分数据框。这些索引值当前存储在一个向量中:

1 18 19 25 26 33 34 41 42 49...

此后,我想将第一个数据框(第 1 - 18 列)添加到所有其他数据框(无需手动操作)。

【问题讨论】:

  • 如果您有您开始使用的数据、所需的输出应该是什么样的、您尝试过什么以及您尝试过的问题,您会得到更好的响应。

标签: r indexing subset


【解决方案1】:

其中一种方法是将拆分向量转换为 2 列矩阵,而不是将其应用于感兴趣的 data.frame。结果,您将获得所需的数据框列表。

# Simulataed data frame with 100 columns
df <- as.data.frame(matrix(1:1000, ncol = 100))

# Splits vector
splits <- c(1, 18, 19, 25, 26, 33, 34, 41, 42, 49, 50, 100)

# Extract columns we need to add to the rest of split data frames
first <- splits[1:2]
rest <- splits[-(1:2)]

# create a matrix with two columns
splits_m <- matrix(rest, ncol = 2, byrow = TRUE)

# make list of data frame base on splits
dfl <- apply(splits_m, 2, function(x) df[, c(x[1]:x[2], first[1]:first[2])])

# access the first data.frame
dfl[[1]]

【讨论】:

    猜你喜欢
    • 2023-04-07
    • 1970-01-01
    • 2021-02-02
    • 1970-01-01
    • 2021-01-12
    • 2022-12-17
    • 1970-01-01
    • 2018-03-19
    • 1970-01-01
    相关资源
    最近更新 更多