【问题标题】:How to combine two or more columns of data table to one column? [duplicate]如何将两列或多列数据表合并为一列? [复制]
【发布时间】:2021-08-04 06:06:43
【问题描述】:

我有一个数据表,看起来像这样:

year <- c("2018", "2018", "2018", "2018")
month <- c("01","01","01","01")
day <- c("01", "02","03","04")
hour <- c("00","01","02","03")
id <- c(8750, 3048, 3593, 8475)
type <- c("ist","plan","ist","plan")

dt.test <- data.table(year, month, day, hour, id, type)

现在我想将 yearmonthdayhour 列合并为一个名为 date 的列,其形式为 "2018-01-01 00""2018-01-02 01" 等。最后,我需要一个包含date(组合一个)、idtype 列的数据表。我知道如何使用paste() 来做到这一点,但还有其他快速有效的方法吗?

【问题讨论】:

  • paste 应该很快。您如何使用它,您的数据有多大?
  • 我会像这样使用它:dt.result$date1 &lt;- paste(dt.test$year, dt.test$month, dt.test$day, sep = "-")dt.result$date &lt;- paste(dt.result$date1, dt.test$hour)... 我的数据表大约是 1GB(我的行和列比我的问题示例多)。所以需要一些时间。
  • tidyr::unite 有帮助吗? dt.test &lt;- tidyr::unite(dt.test, date, year:hour, sep = '-')
  • 谢谢!这比我的paste-version 快。
  • 你有一个data.table,那么为什么不通过引用来创建你的列呢?

标签: r datatable multiple-columns


【解决方案1】:

你可以使用tidyr::unite -

dt.test <- tidyr::unite(dt.test, date, year:hour, sep = '-')
dt.test

#            date   id type
#1: 2018-01-01-00 8750  ist
#2: 2018-01-02-01 3048 plan
#3: 2018-01-03-02 3593  ist
#4: 2018-01-04-03 8475 plan

【讨论】:

  • 这并没有给出指定的格式 - 天和小时之间有一个空格而不是破折号。这将起到相当大的作用,因为您只需要一个粘贴操作而不是两个。
  • 如果你有a look under the hood unite 归结为pastepaste0
猜你喜欢
  • 2018-11-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-05-17
  • 2014-03-08
  • 2018-07-28
  • 2012-07-19
相关资源
最近更新 更多