我有這個資料框
x <- data.frame(
matrix(
c(letters[1:3], c("x", "x", "y") ,
sample(c(rep(1,100),0), size = 1),
sample(c(rep(1,100),0), size = 1),
sample(c(rep(1,100),0), size = 1)), ncol = 3)
)
我想乘以 X 和 Y 組。
我的建議
agg <- aggregate(x$X3,
by = list(x$X2),
FUN = *)
我想用像sum, meanbyt這樣的東西來乘
uj5u.com熱心網友回復:
是sum因為*是prod(對于產品)。
您的示例資料遵循data.frame(matrix()). 一個矩陣只能有一種資料型別。你在矩陣中混合字符和數字資料,矩陣使它成為character類,你不能對字符進行數學運算。這是正確的示例資料和解決方案作業的演示。另請注意,使用by = X["X2"]而不是by = list(x$X2)在結果中提供更好的列名。
(x <- data.frame(
X1 = letters[1:3],
X2 = c("x", "x", "y") ,
X3 = 2:4
))
# X1 X2 X3
# 1 a x 2
# 2 b x 3
# 3 c y 4
aggregate(x$X3, by = x["X2"], FUN = prod)
# X2 x
# 1 x 6
# 2 y 4
uj5u.com熱心網友回復:
使用 prod 或使用帶 * 的 Reduce。還將 X3 轉換為數字并使用單括號(如圖所示)以保留名稱。或者使用聚合公式方法,該方法僅用于 prod,但也適用于 Reduce。
xx <- transform(x, X3 = as.numeric(X3))
aggregate(xx["X3"], by = xx["X2"], FUN = prod)
aggregate(xx["X3"], by = xx["X2"], FUN = Reduce, f = `*`) # same
aggregate(X3 ~ X2, xx, FUN = prod)
一個更好的例子可能是使用 R 附帶的 mtcars:
aggregate(mtcars["mpg"], by = mtcars["cyl"], FUN = prod)
aggregate(mtcars["mpg"], by = mtcars["cyl"], FUN = Reduce, f = `*`) # same
aggregate(mpg ~ cyl, mtcars, FUN = prod)
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/390438.html
