gpt4 book ai didi

R:使用 dcast 时包括没有条目的因素

转载 作者:行者123 更新时间:2023-12-03 15:51:19 25 4
gpt4 key购买 nike

我在数据帧上使用 reshape2 函数 dcast。其中一个变量是某些级别未出现在数据框中的因素,但我会在创建的新列中包含所有值。

例如说我运行以下

library(reshape2)
dataDF <- data.frame(
id = 1:6,
id2 = c(1,2,3,1,2,3),
x = c(rep('t1', 3), rep('t2', 3)),
y = factor(c('A', 'B', 'A', 'B', 'B', 'C'), levels = c('A', 'B', 'C', 'D')),
value = rep(1)
)

dcast(dataDF, id + id2 ~ x + y, fill = 0)

我得到以下
  id id2 t1_A t1_B t2_B t2_C
1 1 1 1 0 0 0
2 2 2 0 1 0 0
3 3 3 1 0 0 0
4 4 1 0 0 1 0
5 5 2 0 0 1 0
6 6 3 0 0 0 1

但我也想包括列 t1_C, t1_D, t2_A 和 t2_D 全是 0

即我想要以下内容
  id id2 t1_A t1_B t1_C t1_D t2_A t2_B t2_C t2_D
1 1 1 1 0 0 0 0 0 0 0
2 2 2 0 1 0 0 0 0 0 0
3 3 3 1 0 0 0 0 0 0 0
4 4 1 0 0 0 0 0 1 0 0
5 5 2 0 0 0 0 0 1 0 0
6 6 3 0 0 0 0 0 0 1 0

此外,作为辅助,是否可以在初始数据框中没有列“值”全是 1 的情况下创建上述内容。基本上只是想将 x & y 在他们自己的列中转换为 1,如果它们存在于该 id 中。

提前致谢

编辑:
最初在 LHS 上有一个变量,Jeremy 在下面回答,但实际上在 LHS 上有不止一个变量,因此编辑了问题以反射(reflect)这一点

最佳答案

尝试添加 drop = FALSE到您的 dcast 调用,以便不会丢弃未使用的因子级别:

dcast(dataDF, id ~ x + y, fill = 0, drop = FALSE)

id t1_A t1_B t1_C t1_D t2_A t2_B t2_C t2_D
1 1 1 0 0 0 0 0 0 0
2 2 0 1 0 0 0 0 0 0
3 3 1 0 0 0 0 0 0 0
4 4 0 0 0 0 0 1 0 0
5 5 0 0 0 0 0 1 0 0
6 6 0 0 0 0 0 0 1 0

顺便说一句,是的,我们只需要告诉 dcast你想用什么函数来 aggregate ,在这种情况下,您需要 length :
data2 <- dataDF[,1:3]
dcast(data2, id ~ x + y, fill = 0, drop = FALSE, fun.aggregate = length)

对于您的编辑,我会使用 tidyrdplyr而不是 reshape2 :
library(tidyr)
library(dplyr)

dataDF %>% left_join(expand.grid(x = levels(dataDF$x), y = levels(dataDF$y)), .) %>%
unite(z, x, y) %>%
spread(z, value, fill = 0) %>%
na.omit

首先,我们使用 expand.grid 完成 x 和 y 的所有组合并合并,然后我们 unite将它们合并为一列 z,然后我们 spread它们出来,然后从 id 列中删除 NA:
  id id2 t1_A t1_B t1_C t1_D t2_A t2_B t2_C t2_D
1 1 1 1 0 0 0 0 0 0 0
2 2 2 0 1 0 0 0 0 0 0
3 3 3 1 0 0 0 0 0 0 0
4 4 1 0 0 0 0 0 1 0 0
5 5 2 0 0 0 0 0 1 0 0
6 6 3 0 0 0 0 0 0 1 0

关于R:使用 dcast 时包括没有条目的因素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33040961/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com