如何提取R语言strsplit()分割结果中的第一列与第二列?
提取strsplit结果列表中的列元素
嗨,针对你这个从strsplit生成的列表里提取对应列的需求,我给你分享几种常用的R语言实现方法:
首先先确认我们的初始数据:
foo = c("1x2","3x4","5x6","7x8","9x10") goo = strsplit(foo, "x")
方法1:用sapply快速提取
这是最基础也最常用的方法,sapply可以遍历列表的每个元素,提取指定位置的元素并自动整理成向量:
# 提取第一列并转为数值型 first_col <- as.numeric(sapply(goo, "[[", 1)) first_col # [1] 1 3 5 7 9 # 提取第二列并转为数值型 second_col <- as.numeric(sapply(goo, "[[", 2)) second_col # [1] 2 4 6 8 10
这里的"[["是提取列表元素的索引函数,指定第二个参数1或2就对应取每个子列表的第1、2个元素。
方法2:转成矩阵后提取列
如果后续需要对这些数据做矩阵相关操作,可以先把列表转成矩阵,再按列提取:
# 将列表转为字符矩阵 goo_mat <- do.call(rbind, goo) goo_mat # [,1] [,2] # [1,] "1" "2" # [2,] "3" "4" # [3,] "5" "6" # [4,] "7" "8" # [5,] "9" "10" # 提取并转换数值 first_col <- as.numeric(goo_mat[, 1]) second_col <- as.numeric(goo_mat[, 2])
方法3:用purrr包(tidyverse风格)
如果你平时习惯用tidyverse工具链,purrr包的map系列函数会更直观:
library(purrr) # 提取第一列(直接转整数) first_col <- map_int(goo, 1) # 提取第二列(因为有10,用map_dbl转数值更稳妥) second_col <- map_dbl(goo, 2)
这几种方法都能满足你的需求,你可以根据自己的代码风格和后续操作选择合适的方式~
内容的提问来源于stack exchange,提问作者Rene Reitsma
相关产品推荐
相关产品推荐

