如何将两个大字符向量组合成一个数据帧?

时间:2017-03-26 15:55:36

标签: r

我有两个大字符向量,如下所示:

a<- c("Product1_name   Product1_desc       Product1_color","Product2_name   Product2_desc       Product2_color","Product3_name   Product3_desc       Product3_color")

b<- c("16 MAR 2017","15 MAR 2017","20 MAR 2017")

如何将a和b组合成一个数据框(4列),如下所示:

enter image description here

2 个答案:

答案 0 :(得分:1)

我们可以使用read.table将“a”拆分为三列,将cbind拆分为“b”

cbind(b, read.table(text=a, header=FALSE))

答案 1 :(得分:1)

使用stringrdata.table包的潜在解决方案如下

library(data.table)
library(stringr)

a <- c("Product1_name   Product1_desc       Product1_color","Product2_name   Product2_desc       Product2_color","Product3_name   Product3_desc       Product3_color")
b <- c("16 MAR 2017","15 MAR 2017","20 MAR 2017")

# remove multiple consecutive spaces from a
a <- str_replace_all(a, "( )+", " ")

# create data table
dt <- data.table(
  date = b,
  product_tmp = a
)

# split temporary product column in three columns
dt[, c("product_name", "product_desc", "product_color") := tstrsplit(product_tmp, " ")]

# remove temporary product column
dt[, product_tmp := NULL]

# show data table
dt