![](/img/trans.png)
[英]How to count the number of observations in a column while defining a function in R?
[英]How to count number of observations in each column in a grouped dataframe in r
我有一個由地球化學樣本結果組成的數據框,其中包括以下變量:
Year, Zone, *48 analyzed elements*, *more information*.
我想知道每年在每個區域為每個元素收集了多少樣本。 所以基本上,我想要一個看起來像這樣的表:
Year,Zone,Ag_ppm, ..., Zr_ppm
1981, ZoneA, 0, ..., 0
1981, ZoneB, 20, ..., 0
1983, ZoneA, 0, ..., 150
我嘗試了以下方法:
Elt_count <- SoilGeology %>%
group_by(Year, Zone) %>%
summarise_at(vars(Ag_ppm:Zr_ppm),funs(sum)) %>%
select(Year, Zone, Ag_ppm:Zr_ppm)
它有效,但它沒有給我我想要的信息(我不想要樣本的累積總和,而是每個樣本的計數)。 然后我嘗試過:
Elt_count <- SoilGeology %>%
group_by(Year, Zone) %>%
summarise_at(vars(Ag_ppm:Zr_ppm),funs(n)) %>%
select(Year, Zone, Ag_ppm:Zr_ppm)
但我收到以下錯誤: Error in summarise_impl(.data, dots) :
n() does not take arguments
我也試過:
d <- SoilGeology %>%
group_by(Year, Zone) %>%
summarise_all(n) %>%
select(Year, Zone, Ag_ppm:Zr_ppm)
但我得到了與上面相同的錯誤: Error in summarise_impl(.data, dots) :
n() does not take arguments
並且還嘗試了計數:
Elt_count <- SoilGeology %>%
group_by(Year, Zone) %>%
count(Au_ppm:Zr_ppm, na.rm = TRUE) %>%
select(Year, Zone, Ag_ppm:Zr_ppm)
但是,我收到錯誤:
Error in mutate_impl(.data, dots) : Evaluation error: NA/NaN argument.
In addition: Warning messages:
1: In Au_ppm:Zr_ppm :
numerical expression has 52 elements: only the first used
2: In Au_ppm:Zr_ppm :
numerical expression has 52 elements: only the first used
有人對這些錯誤有解釋嗎? 或者對我的問題有更好的解決方案?
謝謝!
也許下面的代碼是你想要的。
library(dplyr) count(SoilGeology, year, zone, Ag_ppm:Zr_ppm)
或等效於管道功能
SoilGeology %>% count(SoilGeology, year, zone, Ag_ppm:Zr_ppm)
交替,
SoilGeology %>% group_by(year, zone, Ag_ppm:Zr_ppm) %>% summarise(number = n())
或者
SoilGeology %>% group_by(year, zone, Ag_ppm:Zr_ppm) %>% tally()
如果錯誤仍然存在,則應檢查變量的“class()”。 值可能需要強制轉換為數字。 如果需要,請嘗試variable -> as.numeric(variable)
試。
sum
添加數字, n()
和count()
計數行。 如果大於 0 的數字對您有特殊意義,您需要告訴 R。 計算滿足條件的事物數量的經典方法是sum(..test for condition..)
,所以如果你想要x
大於0
的元素數量, sum(x > 0)
就可以了。 這是您要應用於所有列的函數:
# reproducible example on built-in data
mtcars %>%
group_by(cyl) %>%
summarize_at(vars(disp:carb), function(x) sum(x > 5))
# for your data
Elt_count <- SoilGeology %>%
group_by(Year, Zone) %>%
summarise_at(vars(Ag_ppm:Zr_ppm), function(x) sum(x > 0))
我不知道你的數據。 如果您也想計算負數,您可能希望將其更改為sum(x != 0)
。 如果有缺失值, sum(x > 0, na.rm = TRUE)
(如果你看?sum
,它確實需要一個na.rm
參數)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.