r - 将数据框从长格式转换为宽格式后,日期变量错误地转换为数字变量

标签 r data.table

我正在处理一个数据框,该数据框包含跨多个时间点的参与者数据。我正在尝试将数据框从长格式转换为宽格式。数据框由属于不同数据类型的变量组成,例如日期和数字。

library(data.table)

SN <- c("AAA", "BBB", "BBB", "CCC", "DDD", "EEE", "DDD")
Timepoint <- c(1, 1, 2, 1, 1, 1, 2)
date <- c("31-Mar-17", "08-Mar-17", "31-Mar-18", "28-Mar-18", "17-Mar-17", "26-Feb-18", "07-Apr-18")
score <- c(13, 16, 17, 9, 14, 15, 15)
age <- c(12, 15, 16, 9, 14, 14, 15)
df <- data.frame(SN, Timepoint, date, score, age)
df$date <- as.Date(df$date, format = "%d-%B-%y")

我使用以下代码将数据从长格式转换为宽格式:

df2 <- dcast(melt(df, id.vars = c("SN", "Timepoint")),
         SN ~ Timepoint + variable, value.var = "value")

由于 R 将所有变量解释为属于通用类型(数字),因此日期变量被错误地转换为数字变量。

以下是我得到的错误输出:

Incorrect Output

我试图实现的正确输出如下:

Correct Output

谢谢!帮助非常感谢!

最佳答案

我们可能还需要在 id.vars 中包含“date”作为 numeric 中的“value”列,通过混合两个类,它可以转换为一个一即数字一。相反,如果我们有两个单独的列并使用 data.table::dcast 中的 value.var(采用多个变量)

dcast(melt(setDT(df), id.vars = c("SN", "Timepoint", "date")),
      SN ~ Timepoint + variable, value.var = c("date", "value"))

根据预期的输出,我们可能只需要dcast

dcast(setDT(df)[], SN ~ Timepoint, value.var = c('date', 'score', 'age'))

关于r - 将数据框从长格式转换为宽格式后,日期变量错误地转换为数字变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50253616/

相关文章:

R函数solve.QP错误 "constraints are inconsistent, no solution!"

regex - 在字符串中的第一个逗号处拆分

r - 数据框列的简单操作

r - 使用 data.table 扩展数据

r - 丢掉前n行

r - R 中的数据表 : the columns to join by must be specified using 'on=' argument error

python - R Keras 是否基于此输出使用 GPU?

r - 仅保留字符串中的值

r - 使用 R 中的 data.table 添加观察计数到聚合

r - 在 x 首先超过 y 的组中过滤