![](/img/trans.png)
[英]Using “dplyr” to calculate specific ratio for for each row of dataframe
[英]Calculate mode for each column in dataframe using lapply dplyr
我正在嘗試創建一個函數,該函數從本質上為我提供MODE ...或MODE-X(第二至第X最常見的值&以及數據幀中每一列的關聯計數。
我不知道自己可能會缺少什么,正在尋找幫助嗎? 我相信這與將變量傳入dplyr函數有關。
library(tidyverse)
myfunct_get_mode = function(x, rank=1){
mytable = dplyr::count(rlang::sym(x), sort = TRUE)
names(mytable)= c('variable','counts')
# return just the rank specified...such as mode or mode -1, etc
result = table %>% dplyr::slice(rlang::sym(rank))
return(result)
}
mtcars %>% lapply(. %>% (function(x) myfunct_get_mode(x, rank=2)))
您的功能存在一些問題:
mtcars %>% lapply(. %>% (function(x) print(x)))
,確保您的x
實際上是mtcars
的整個列。 要獲取列的名稱,請將函數應用於names(mtcars)
。 但是隨后,您還必須指定要處理的數據框。 sym
需要從你使用!!
在rlang::sym(x)
前面。 rank
不是變量名,因此這里不需要rlang::sym
。 table
應該在函數的倒數第二行是mytable
。 因此,它如何工作(盡管可能有更好的方法):
myfunct_get_mode = function(df, x, rank=1){
mytable = count(df, !!rlang::sym(x), sort = TRUE)
names(mytable)= c('variable','counts')
# return just the rank specified...such as mode or mode -1, etc
result = mytable %>% slice(rank)
return(result)
}
names(mtcars) %>% lapply(function(x) myfunct_get_mode(mtcars, x, rank=2))
如果我們需要list
,可以使用map
f1 <- function(dat, rank = 1) {
purrr::imap(dat, ~
dat %>%
count(!! rlang::sym(.y)) %>%
rename_all(~ c('variable', 'counts')) %>%
arrange(desc(counts)) %>%
slice(seq_len(rank))) #%>%
#bind_cols - convert to a data.frame
}
f1(mtcars, 2)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.