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

时间:2025-02-24 15:10:07

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

before = (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)
  1. 使用函数 ((what, args, quote = FALSE, envir = ())
before <- (attr = c(1,30,4,6), type=c('foo_and_bar','foo_and_bar_2'))  
out <- strsplit((before$type),'_and_') 
(rbind, out)
  1. 使用tidyr包
library(dplyr)
library(tidyr)
before <- (attr = c(1, 30 ,4 ,6 ), type = c('foo_and_bar', 'foo_and_bar_2'))
before %>% separate(type, c("foo", "bar"), "_and_")
  1. 使用sapply 以及 "["
before$type_1 < sapply(strsplit((before$type),'_and_'), "[", 1)
before$type_2 < sapply(strsplit((before$type),'_and_'), "[", 2)

或者

before <- (attr = c(1,30,4,6), type=c('foo_and_bar','foo_and_bar_2'))
after <- with(before, (attr = attr))
after <- cbind(after, (t(sapply(out, `[`))))
names(after)[2:3] <- paste("type", 1:2, sep = "_")
  1. 使用unlist后重新划分矩阵
before <- (attr = c(1,30,4,6), type=c('foo_and_bar','foo_and_bar_2'))
tmp <- matrix(unlist(strsplit((before$type), '_and_')), ncol=2,byrow=TRUE) #you should show how many columns you would get after spliting
after <- cbind(before$attr, (tmp))
names(after) <- c("attr", "type_1", "type_2")