R 如何更改/重新构造已固定的数据表格式?

R 如何更改/重新构造已固定的数据表格式?,r,formatting,data.table,R,Formatting,Data.table,我总是会得到这种格式的数据表: set.seed(123) dt <- data.table(date = seq(as.Date('2020-01-01'), by = '1 day', length.out = 365), Germany = rnorm(365, 2, 1), check.names = FALSE) set.seed(123) dt在单独的列中提取月份和日期,并以宽格式获取数据 library(dplyr) dt %>%

我总是会得到这种格式的数据表:

set.seed(123)
dt <- data.table(date = seq(as.Date('2020-01-01'), by = '1 day', length.out = 365),
                 Germany = rnorm(365, 2, 1), check.names = FALSE)
set.seed(123)

dt在单独的列中提取月份和日期,并以宽格式获取数据

library(dplyr)
dt %>%
  mutate(month = format(date, '%b'), 
         date = format(date, '%d')) %>%
  tidyr::pivot_wider(names_from = date, values_from = Germany)
如果要在
data.table
中执行此操作,可以使用
dcast

library(data.table)
dcast(dt[,`:=`(month = format(date, '%b'), date = format(date, '%d'))], 
               month~date, value.var = 'Germany')

在单独的列中提取月份和日期,并以宽格式获取数据

library(dplyr)
dt %>%
  mutate(month = format(date, '%b'), 
         date = format(date, '%d')) %>%
  tidyr::pivot_wider(names_from = date, values_from = Germany)
如果要在
data.table
中执行此操作,可以使用
dcast

library(data.table)
dcast(dt[,`:=`(month = format(date, '%b'), date = format(date, '%d'))], 
               month~date, value.var = 'Germany')

下面是使用
data.table
解决此问题的另一种方法。 请注意,
month.abb
r
中的内置变量。 使用
factor
函数和
month.abb
作为级别,可以对月份进行正确排序

library(data.table)

dcast(dt[, month := factor(months(date, abbr = TRUE), month.abb)], 
      month ~ mday(date), value.var = 'Germany')

 #    month     1     2    3    4    5    6    7    8    9   10   11    12 ...
 # 1:   Jan  1.44  1.77 3.56 2.07 2.13 3.72 2.46 0.73 1.31 1.55 3.22  2.36
 # 2:   Feb  1.70  2.90 2.88 2.82 2.69 2.55 1.94 1.69 1.62 1.31 1.79  0.73
 # 3:   Mar  2.38  1.50 1.67 0.98 0.93 2.30 2.45 2.05 2.92 4.05 1.51 -0.31
 # ... 

下面是使用
data.table
解决此问题的另一种方法。 请注意,
month.abb
r
中的内置变量。 使用
factor
函数和
month.abb
作为级别,可以对月份进行正确排序

library(data.table)

dcast(dt[, month := factor(months(date, abbr = TRUE), month.abb)], 
      month ~ mday(date), value.var = 'Germany')

 #    month     1     2    3    4    5    6    7    8    9   10   11    12 ...
 # 1:   Jan  1.44  1.77 3.56 2.07 2.13 3.72 2.46 0.73 1.31 1.55 3.22  2.36
 # 2:   Feb  1.70  2.90 2.88 2.82 2.69 2.55 1.94 1.69 1.62 1.31 1.79  0.73
 # 3:   Mar  2.38  1.50 1.67 0.98 0.93 2.30 2.45 2.05 2.92 4.05 1.51 -0.31
 # ... 

谢谢你的快速回答。如果我对
dplyr
包使用第一种方法,并将其定义为一个新的数据表
dt.test
,我会得到以下错误消息:error in exists(what,where,inherits=FALSE)invalid first arguments是否使用相同的数据?似乎是环境问题。你能重新启动R然后再试一次吗?现在它工作了。非常感谢。谢谢你的快速回答。如果我对
dplyr
包使用第一种方法,并将其定义为一个新的数据表
dt.test
,我会得到以下错误消息:error in exists(what,where,inherits=FALSE)invalid first arguments是否使用相同的数据?似乎是环境问题。你能重新启动R然后再试一次吗?现在它工作了。非常感谢。