如何使用 dcast "fill" 变量

How to "fill" a variable with dcast

作为 car-sharing 研究的一部分,我使用的 table 看起来像这样:

这里的问题是不应该有两条线:这实际上是一个单一的旅程(相同的driver,相同的出发时间)并且"C"应该在第一行,在 Passenger2 列中。

因此,我试图在 Date/Hour_dep/Driver 相同时自动 "fill" Passenger2 列。 ID_Dep是另一回事,它是为每一行自动生成的,CDE002根本不应该存在。

据我所知,dcast 是我最好的解决方法。但是我...不知道如何正确使用它。实际上,我什至不确定 dcast 是我应该使用的。 在某些时候,使用我的真实 table,我设法得到一个意外事件 table,其中一列代表 Passenger2 的每个可能值。如果我能够从最左边的列开始提取第一个 non-NA 值,那么我就会得到我想要的 table。但是我也没拿到。

这是重新创建 table 和我的 totally-not-working dcast 的代码,欢迎任何帮助。

test_iddep<-c("AAA1","BBB2")
test_Date<-c("01/05/2019","01/05/2019")
test_hourdep <- c("8:00","8:00")
test_driv<-c("A","A")
test_pass1<-c("B","C")
test_pass2<-c(NA,NA)

test_table <- data.frame(test_iddep,test_Date,test_hourdep,test_driv,test_pass1,test_pass2)

table_arranged <- dcast(test_table, test_driv + test_Date + test_hourdep + test_pass1 ~ test_pass2, 
                        margins=c("test_driv","test_Date","test_hourdep")) 

我怀疑您可以使用多种不同的方法(而且可能更好)。

如果您确实想使用 dcast,这里可能是一种方法:

首先,我会 melt 基于日期、小时和 driver 的数据。然后将为这些唯一组合中的每一个创建一个 id。然后对于每个 id,将为每个乘客添加一个序列号。然后 dcast:

library(reshape2)

test_table <- data.frame(
  test_iddep = c("AAA1", "BBB2", "CCC3", "DDD4", "EEE5"),
  test_Date = c("01/05/2019", "01/05/2019", "01/07/2019", "01/07/2019", "01/07/2019"),
  test_hourdep = c("8:00", "8:00", "10:00", "10:00", "10:00"),
  test_driv = c("A", "A", "B", "B", "B"),
  test_pass1 = c("B", "C", "D", "E", "F")
)

x <- melt(test_table[-1], id.vars = c("test_driv", "test_Date", "test_hourdep"))
x$id <- cumsum(!duplicated(x[1:3]))
x$time <- ave(x$id, x$id, FUN=seq_along)
dcast(x, test_driv + test_Date + test_hourdep ~ time, value.var = "value")

  test_driv  test_Date test_hourdep 1 2    3
1         A 01/05/2019         8:00 B C <NA>
2         B 01/07/2019        10:00 D E    F

如果这是您想要的输出,请告诉我。我已经删除了 test_iddep,因为听起来您的问题不需要这样做。