【发布时间】:2017-03-22 23:06:58
【问题描述】:
我想转换我的数据,以便使用 dcast 获得平均存活率,但似乎不可能:
数据
PassengerId Survived Pclass Name Sex Age SibSp Parch Ticket Fare Cabin Embarked
1 0 3 Braund, Mr. Owen Harris male 22 1 0 A/5 21171 7.25 S
2 1 1 Cumings, Mrs. John Bradley (Florence Briggs Thayer) female 38 1 0 PC 17599 71.2833 C85 C
3 1 3 Heikkinen, Miss. Laina female 26 0 0 STON/O2. 3101282 7.925 S
示例数据代码:
df <- structure(list(PassengerId = 1:6, Survived = structure(c(1L,
2L, 2L, 2L, 1L, 1L), .Label = c("0", "1"), class = "factor"),
Pclass = c(3L, 1L, 3L, 1L, 3L, 3L), Name = c("Braund, Mr. Owen Harris",
"Cumings, Mrs. John Bradley (Florence Briggs Thayer)", "Heikkinen, Miss. Laina",
"Futrelle, Mrs. Jacques Heath (Lily May Peel)", "Allen, Mr. William Henry",
"Moran, Mr. James"), Sex = c("male", "female", "female",
"female", "male", "male"), Age = c(22, 38, 26, 35, 35, NA
), SibSp = c(1L, 1L, 0L, 1L, 0L, 0L), Parch = c(0L, 0L, 0L,
0L, 0L, 0L), Ticket = c("A/5 21171", "PC 17599", "STON/O2. 3101282",
"113803", "373450", "330877"), Fare = c(7.25, 71.2833, 7.925,
53.1, 8.05, 8.4583), Cabin = c("", "C85", "", "C123", "",
""), Embarked = c("S", "C", "S", "S", "S", "Q")), .Names = c("PassengerId",
"Survived", "Pclass", "Name", "Sex", "Age", "SibSp", "Parch",
"Ticket", "Fare", "Cabin", "Embarked"), row.names = c(NA, 6L), class = "data.frame")
目前的功能:
reshape2::dcast(titanic, Sex ~ ., mean)
期望的输出:
Row Label Average of Survived
Male 3.14156
Female 3.14156
目前,它返回此错误:
Sex .
1 female NA
2 male NA
Warning messages:
1: In mean.default(.value[0], ...) :
argument is not numeric or logical: returning NA
我认为这可能与 reshape 中的 cast 函数有关,但这可能与 reshape2 有关吗?
【问题讨论】:
-
在您的幸存列中,1 表示幸存,0 表示未幸存吗?
-
是的,没错。我会假设你应该能够轻松地做到这一点,但也许它在 data.table 中,而不是 reshape2
-
能否提供更多数据行(尤其是《性与幸存者》)?我认为其他列对您的计算并不重要。
-
dcast通常用于旋转到多个列(也许总是?)。如果您只需要一列,请使用DT[, mean(Survived == "1"), by=Sex]或类似名称。如果您使用的是 reshape2 而不是 data.table,那么还有来自 base... 或tapply的aggregate。 -
@Frank 是的,我想进一步澄清您是否应该为此使用 dcast,因为使用 pandas 数据透视表很容易做到,而且看起来您可以使用(从重塑纸):演员(ffm,治疗〜.,长度)治疗(全部)1 2 3 1 1159 2 1157 3 1155
标签: r data.table dplyr reshape2