我有两个大字符向量,如下所示:
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列),如下所示:
答案 0 :(得分:1)
我们可以使用read.table
将“a”拆分为三列,将cbind
拆分为“b”
cbind(b, read.table(text=a, header=FALSE))
答案 1 :(得分:1)
使用stringr
和data.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