我想为具有长变量名和级别的数据集计算大量手段。由于attach被皱眉了,所以我想知道是否可以使用with()
块,但是在关闭该块之后是否可以使用结果。
这是我要询问的示例,但使用$
连接器执行。缅因州各种湖泊中的汞含量:
Y_O=mean(Maine$Mercury[Maine$Lake_Type=="Oligotropic"])
Y_M=mean(Maine$Mercury[Maine$Lake_Type=="Mesotropic"])
Y_E=mean(Maine$Mercury[Maine$Lake_Type=="Eutropic"])
我发现读者很难知道我的意思。
我想这样做:
with(Maine, {
YGrand <- mean(Mercury)
Y_O <- mean(Mercury[Lake_Type == "Oligotropic"])
Y_M <- mean(Mercury[Lake_Type == "Mesotropic"])
Y_E <- mean(Mercury[Lake_Type == "Eutropic"])
})
我已经超出本章的页面限制,所以我没有空间来介绍管道。在我的脑海中,我似乎想起有人在分配中使用<-
以外的其他运算符,从而将结果提升到常规用户级别。有这样的事吗?
答案 0 :(得分:2)
使用> aggregate(mtcars$hp, list(cyl = mtcars$cyl) ,mean)
cyl x
1 4 82.63636
2 6 122.28571
3 8 209.21429
将函数应用于列表中元素定义的组:
SELECT ChatSessionID,
COUNT(IF(Metrics = "Met001", Metrics, NULL)) AS Met001,
COUNT(IF(Metrics = "Met002", Metrics, NULL)) AS Met002,
COUNT(IF(Metrics = "Met003", Metrics, NULL)) AS Met003,
COUNT(IF(Metrics = "Met004", Metrics, NULL)) AS Met004,
COUNT(IF(Metrics = "Met005", Metrics, NULL)) AS Met005,
COUNT(IF(Metrics = "Met006", Metrics, NULL)) AS Met006,
COUNT(IF(Metrics = "Met007", Metrics, NULL)) AS Met007,
COUNT(IF(Metrics = "Met008", Metrics, NULL)) AS Met008,
COUNT(IF(Metrics = "Met009", Metrics, NULL)) AS Met009,
COUNT(IF(Metrics = "Met010", Metrics, NULL)) AS Met010,
COUNT(IF(Metrics = "Met011", Metrics, NULL)) AS Met011,
COUNT(IF(Metrics = "Met012", Metrics, NULL)) AS Met012,
COUNT(CASE WHEN Metrics="Met003" And Metrics="Met004" THEN Metrics ELSE NULL END) AS Met014
FROM
botdata b
WHERE
b.Metrics BETWEEN "Met001" AND "Met014"
GROUP BY
ChatSessionID;
答案 1 :(得分:0)
类似下面的方法可能有效,但我会找到另一种方法
x = with(mtcars, {
c_all = mean(mpg)
c_6 = mean(mpg[cyl == 6])
c_4 = mean(mpg[cyl == 4])
c_8 = mean(mpg[cyl == 8])
data.frame(c_all, c_4, c_6, c_8)
})
list2env(x, envir = .GlobalEnv)
c_4
#[1] 26.66364
c_6
#[1] 19.74286
c_8
#[1] 15.1
c_all
#[1] 20.09062