如何在R中从列无序的数据框选取最后一个编号colN列?
问题与解决方案
给定以下R代码生成的乱序数据框,需要选取colN系列列中编号N最大的列(本例为col5):
set.seed(25) x = data.frame(col1 = rnorm(5), col2 = rnorm(5), col3 = rnorm(5), col4 = rnorm(5), col5 = rnorm(5), other_data1 = sample(letters, 5), other_data2 = sample(letters, 5), other_data3 = sample(letters, 5)) x = x[ ,sample(names(x))]
Base R 实现
通过提取列名中的数字、筛选最大值,再匹配目标列:
# 提取所有col开头列的编号数字 col_numbers <- as.integer(sub("col", "", grep("^col", names(x), value = TRUE))) # 找到最大编号 max_col <- max(col_numbers) # 选取对应列 target_col <- x[, paste0("col", max_col)]
也可以合并为一行简洁写法:
x[, paste0("col", max(as.integer(sub("col", "", grep("^col", names(x), value = TRUE)))))]
tidyverse 实现
结合dplyr和stringr工具完成筛选:
library(dplyr) library(stringr) # 分步实现更清晰 max_col_number <- names(x) %>% str_subset("^col") %>% # 筛选col开头的列名 str_extract("\\d+") %>% # 提取编号数字 as.integer() %>% max() # 选取目标列 x %>% select(all_of(str_c("col", max_col_number)))
或者合并为链式调用:
x %>% select(str_c("col", max(as.integer(str_extract(names(.), "^col(\\d+)", group = 1)))))
内容的提问来源于stack exchange,提问作者NM_
相关产品推荐
相关产品推荐

