【问题标题】:How to combine two large character vectors into one data frame?如何将两个大字符向量组合成一个数据帧?
【发布时间】:2017-03-27 00:03:19
【问题描述】:

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

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 列),如下所示:

【问题讨论】:

  • data.frame(b, do.call(rbind, strsplit(a, '\\s+')))

标签: r


【解决方案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

【讨论】:

    【解决方案2】:

    我们可以用read.table把'a'分成三列,用cbind和'b'分开

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-05-29
      • 2017-04-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-20
      相关资源
      最近更新 更多