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. 使用内置函数
    do.call()
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)

使用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 = "_")
  1. 使用stringr包的str_split_fixed函数
    str_split_fixed()
library(stringr)
str_split_fixed(before$type, "_and_", 2)
  1. 使用tidyr包

separate()

library(tidyr)
separate(data, col, into, sep = "[^[:alnum:]]+", remove = TRUE, convert = FALSE, extra = "warn", fill = "warn", ...)

data: 数据框格式
col: 要分解的列,可以是列名c(“col1”, “col2”),也可以是位置c(1,2)
into: 分解后的列名
sep: 分隔符
remove: 去除被分解的列

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。
禁止转载,如需转载请通过简信或评论联系作者。

推荐阅读更多精彩内容

  • R中根据匹配原则将一列拆分为几列的方法 例如我们需要将一下数据的第二列从and处拆分为两列: before = d...
    NAome阅读 2,731评论 0 0
  • 《R数据科学》的再次回顾学习,以及使用tidyverse过程中的一些new tricks学习记录。 [TOC] 前...
    Dawn_WangTP阅读 1,326评论 0 11
  • 使用GEOquery包 肖恩戴维斯 2014年9月21日 1GEO概述 1.1平台 1.2样品 1.3系列 1.4...
    Greatji阅读 1,003评论 0 1
  • 向量A <- c(1:3)B <- seq(from=,to=,by=)D <- rep(0,5) append ...
    Jachin111阅读 1,301评论 0 0
  • 1.url: 要求为String类型的参数,(默认为当前页地址)发送请求的地址。 2.type: 要求为Strin...
    b2e16cc43137阅读 306评论 0 2