r - 计算每列的百分位数

标签 r dplyr

例如,我想计算此列的百分位数:

list_of_col <- total[ -c(2:8,16:21) ]

我知道如何计算一列上的百分位数(B 是其分组所依据的列,例如 B 的索引为 1,A 是 list_of_col 中的列):

total<- total %>%
  group_by(B) %>%
  mutate(A = rank(A)/length(A))

我正在寻找类似的东西,但我不知道用什么来代替 X

total<- total %>%
  group_by(B) %>%
  mutate_at(list_of_col, X )

最佳答案

dplyr::mutate_at 已被取代。您仍然可以使用它,但这里有一个更“现代”的变体。

library("tidyverse")

set.seed(1234)

n <- 100

total <- tibble(
  B = sample(letters, n, replace = TRUE),
  X1 = rnorm(n),
  X2 = rnorm(n),
  X3 = rnorm(n)
)

total %>%
  group_by(B) %>%
  mutate(
    across(X1:X3, percent_rank)
  )
#> # A tibble: 100 × 4
#> # Groups:   B [26]
#>    B        X1    X2    X3
#>    <chr> <dbl> <dbl> <dbl>
#>  1 p     0     0.25  0.5  
#>  2 z     0.25  0.5   0    
#>  3 v     0.5   0.833 0.5  
#>  4 e     0.667 1     1    
#>  5 l     0     0     1    
#>  6 o     0.25  0     1    
#>  7 i     0.5   0     1    
#>  8 e     1     0.333 0.667
#>  9 f     0.8   0.2   0.6  
#> 10 p     0.25  1     0    
#> # … with 90 more rows

reprex package于2022年7月9日创建(v2.0.1)

我使用了dplyr::percent_rank,而不是你的百分位函数;有了它,百分位数从 0 开始,而不是 1/length(x)

关于r - 计算每列的百分位数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72924062/

相关文章:

r - 使用 data.table 计算百分比和其他函数

r - 按条件过滤数据框,包括该条件之后的数据

r - 如何从 Sys.info() 中提取用户名?

r - 来自两列数据帧的简单网络/集群成员资格

javascript - Node.JS-R,Python 繁重计算识别回调何时返回并存储该结果

r - dplyr 中的 mutate_each/summarise_each : how do I select certain columns and give new names to mutated columns?

r - 如何用月份和 NA 值填充 R 中的数据框

r - R编程中的下标越界错误

r - `dplyr` 中跨列的多个连续操作的语法

r - 如何将 R 中数据帧中的行与 dplyr 配对?