gpt4 book ai didi

r - 可以在没有聚合函数的情况下使用 dcast 吗?

转载 作者:行者123 更新时间:2023-12-02 08:23:06 24 4
gpt4 key购买 nike

Possible Duplicate:
This R reshaping should be simple, but

dcast来自reshape2无需公式即可工作,不存在重复项。以这些示例数据为例:

df <- structure(list(id = c("A", "B", "C", "A", "B", "C"), cat = c("SS", 
"SS", "SS", "SV", "SV", "SV"), val = c(220L, 222L, 223L, 224L,
225L, 2206L)), .Names = c("id", "cat", "val"), class = "data.frame", row.names = c(NA,
-6L))

我想dcast这些数据只是将值制成表格,而不对 value.var 应用任何函数包括默认的length .

在这种情况下,它工作得很好。

> dcast(df, id~cat, value.var="val")
id SS SV
1 A 220 224
2 B 222 225
3 C 223 2206

但是当存在重复变量时,fun默认为length 。有办法避免吗?

df2 <- structure(list(id = c("A", "B", "C", "A", "B", "C", "C"), cat = c("SS", 
"SS", "SS", "SV", "SV", "SV", "SV"), val = c(220L, 222L, 223L,
224L, 225L, 220L, 1L)), .Names = c("id", "cat", "val"), class = "data.frame", row.names = c(NA,
-7L))

> dcast(df2, id~cat, value.var="val")
Aggregation function missing: defaulting to length
id SS SV
1 A 1 1
2 B 1 1
3 C 1 2

理想情况下,我要寻找的是添加 fun = NA ,如不要尝试聚合 value.var 。 dcasting df2 时我想要的结果:

 id  SS  SV
1 A 220 224
2 B 222 225
3 C 223 220
4. C NA 1

最佳答案

我认为没有办法直接做到这一点,但我们可以添加一个额外的列来帮助我们

df2 <- structure(list(id = c("A", "B", "C", "A", "B", "C", "C"), cat = c("SS", 
"SS", "SS", "SV", "SV", "SV", "SV"), val = c(220L, 222L, 223L,
224L, 225L, 220L, 1L)), .Names = c("id", "cat", "val"), class = "data.frame", row.names = c(NA,
-7L))

library(reshape2)
library(plyr)
# Add a variable for how many times the id*cat combination has occured
tmp <- ddply(df2, .(id, cat), transform, newid = paste(id, seq_along(cat)))
# Aggregate using this newid and toss in the id so we don't lose it
out <- dcast(tmp, id + newid ~ cat, value.var = "val")
# Remove newid if we want
out <- out[,-which(colnames(out) == "newid")]
> out
# id SS SV
#1 A 220 224
#2 B 222 225
#3 C 223 220
#4 C NA 1

关于r - 可以在没有聚合函数的情况下使用 dcast 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12831524/

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