You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用R语言提取数据集前4列及后续每第7列的简易代码

在R中提取特定列:保留前4列+第4列后每第7列

嘿,这个需求很清晰,咱们用R轻松就能实现。先结合你的示例数据,一步步来搞定它:

首先,先把你的示例数据集定义好(方便测试):

# 示例数据集
example_df <- data.frame(
  txt1 = c(1,2,3,4), 
  txt2 = c(1,2,3,4), 
  txt3 = c(1,2,3,4), 
  txt4 = c(1,2,3,4), 
  a = c(1,2,3,4), 
  b = c(1,2,3,4), 
  c = c(1,2,3,4), 
  d = c(1,2,3,4), 
  e = c(1,2,3,4), 
  f = c(1,2,3,4), 
  g = c(1,2,3,4),
  h = c(1,2,3,4), 
  i = c(1,2,3,4), 
  j = c(1,2,3,4)
)

接下来是核心逻辑:我们需要合并两类列的索引——前4列,以及第4列之后每隔6列取一列(也就是从第5列开始,步长为7的列)。用seq()函数可以轻松生成后者的索引,然后和前4列的索引组合起来即可:

# 生成目标列的索引:前4列 + 第5列开始每7列取一列
target_cols <- c(1:4, seq(from = 5, to = ncol(example_df), by = 7))

# 提取指定列
filtered_df <- example_df[, target_cols]

# 查看结果
print(filtered_df)

运行这段代码后,你会得到期望的输出:仅保留txt1、txt2、txt3、txt4、a、h列的数据框。

如果你的数据是从外部文件(比如CSV)读取的大型数据集,只需要把example_df换成你的数据集对象就行,逻辑完全一致:

# 示例:读取CSV并提取列
# raw_data <- read.csv("your_large_data.csv")
# target_cols <- c(1:4, seq(from = 5, to = ncol(raw_data), by = 7))
# filtered_data <- raw_data[, target_cols]

内容的提问来源于stack exchange,提问作者JurreS

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.09 15:43:12