美文网首页
R中根据特定字符将一列拆分为几列的方法

R中根据特定字符将一列拆分为几列的方法

作者: 11的雾 | 来源:发表于2022-02-10 20:52 被阅读0次

R中根据匹配原则将一列拆分为几列的方法

例如我们需要将一下数据的第二列从and处拆分为两列:

before = data.frame(attr = c(1,30,4,6), type=c('foo_and_bar','foo_and_bar_2'))

attr          type

1    1  foo_and_bar

2  30 foo_and_bar_2

3    4  foo_and_bar

4    6 foo_and_bar_2

==>

  attr type_1 type_2

1    1    foo    bar

2  30    foo  bar_2

3    4    foo    bar

4    6    foo  bar_2

1. 使用stringr包的str_split_fixed函数

library(stringr)

str_split_fixed(before$type, "_and_", 2)

2. 使用do.call函数 (do.call(what, args, quote = FALSE, envir = parent.frame()))

before <- data.frame(attr = c(1,30,4,6), type=c('foo_and_bar','foo_and_bar_2')) 

out <- strsplit(as.character(before$type),'_and_')

do.call(rbind, out)

3. 使用tidyr包

library(dplyr)

library(tidyr)

before <- data.frame(attr = c(1, 30 ,4 ,6 ), type = c('foo_and_bar', 'foo_and_bar_2'))

before %>% separate(type, c("foo", "bar"), "_and_")

4. 使用sapply 以及 "["

before$type_1 < sapply(strsplit(as.character(before$type),'_and_'), "[", 1)

before$type_2 < sapply(strsplit(as.character(before$type),'_and_'), "[", 2)

或者

before <- data.frame(attr = c(1,30,4,6), type=c('foo_and_bar','foo_and_bar_2'))

after <- with(before, data.frame(attr = attr))

after <- cbind(after, data.frame(t(sapply(out, `[`))))names(after)[2:3] <- paste("type", 1:2, sep = "_")

5. 使用unlist后重新划分矩阵

before <- data.frame(attr = c(1,30,4,6), type=c('foo_and_bar','foo_and_bar_2'))

tmp <- matrix(unlist(strsplit(as.character(before$type), '_and_')), ncol=2,byrow=TRUE) #you should show how many columns you would get after spliting

after <- cbind(before$attr, as.data.frame(tmp))names(after) <- c("attr", "type_1", "type_2")

标签: R

相关文章

  • R中根据特定字符将一列拆分为几列的方法

    R中根据匹配原则将一列拆分为几列的方法 例如我们需要将一下数据的第二列从and处拆分为两列: before = d...

  • golang fmt(格式换 I O接口)

    基本模式 fmt 方法可以大致分为 print, scan两类, 根据基础方法可以构建特定方法。 Print 将参...

  • 2022-04-18 table,tab固定单元(格)处理

    1、 需求描述 固定table 中的某一列或者某几列 固定tab中的某一列或者某几列 2、需求分析 需求只能在边界...

  • mysql分表真得能提升查询性能吗

    首先将存储引擎限定在innodb 2种方式分表 水平分表,根据某一列或者某几列将表按行分割到多张表中,达到减少每张...

  • 32.Python字符串方法split

    在Python的常用字符串方法中,split无疑是最常用的一个。它的作用是将字符串分拆为序列。字符串对象调用方法如...

  • 各种常用的处理命令

    提取染色体片段 提取文件中的某几列 根据位置提取vcf文件对应位点的信息 提取某一列数值满足条件的列 提取某些样本...

  • 正则表达式-字符类

    字符类提供了一种只匹配特定字符集的一个字符的方法。字符类通过方括号把一列字符或一个范围括在一起。 匹配模式[aei...

  • 0基础学习字符串上的方法(详解)

    字符串的方法 1. 用于访问字符串中特定字符的方法 charAt()和charCodeAt() 都接收一个参数: ...

  • [R]合并多列数据

    将dataframe中的几列合并为一列总是忘记这个操作,记在这里备忘 额外一句加载超大的tsv.gz数据,可以不用...

  • 根据特定的字符分割字符串

    在开发的过程中,我们有时需要根据字符串中的某个特殊的字符来截取字符串,这时,我们可以使用这个方法 - (NSArr...

网友评论

      本文标题:R中根据特定字符将一列拆分为几列的方法

      本文链接:https://www.haomeiwen.com/subject/aejokrtx.html