r - 使用 R 在多个列上迭代操作

标签 r

我有一个数据库,其中包含居住在不同社区的每个种族群体的人口信息,例如:

Neighborhood Race1 Race2 Race3
  <chr>        <dbl> <dbl> <dbl>
1 A               19     1    16
2 B               20    17     2
3 C               15     2     7
4 D               17     4    15
5 E               15    20    14

因此,我想计算任何邻域的 Race1、2 和 3 的百分比。为此,我使用了这段代码:

#Firstly, I calculate the total of population by neighborhood.
df$Total=df$Race1+df$Race2+df$Race3
#Then, start the calculation of percentages
df$Race1_pr=df$Race1/df$Total
df$Race2_pr=df$Race2/df$Total
df$Race3_pr=df$Race3/df$Total
#And I obtain this:
head(df)
  Neighborhood Race1 Race2 Race3 Total Race1_pr Race2_pr Race3_pr
  <chr>        <dbl> <dbl> <dbl> <dbl>    <dbl>    <dbl>    <dbl>
1 A               19     1    16    36    0.528   0.0278   0.444 
2 B               20    17     2    39    0.513   0.436    0.0513
3 C               15     2     7    24    0.625   0.0833   0.292 
4 D               17     4    15    36    0.472   0.111    0.417 
5 E               15    20    14    49    0.306   0.408    0.286 

结果是正确的,但是,例如,如果我要分析 100 场比赛,我现在使用的代码将非常乏味,既要计算总人口又要计算百分比。我想知道是否有一种方法可以用我的代码迭代我目前正在遵循的过程。

最佳答案

一个可能的解决方案,经过编辑以纳入@stefan 提供的建议,使用 rowSums:

library(tidyverse)

df <- data.frame(
  stringsAsFactors = FALSE,
  Neighborhood = c("A", "B", "C", "D", "E"),
  Race1 = c(19L, 20L, 15L, 17L, 15L),
  Race2 = c(1L, 17L, 2L, 4L, 20L),
  Race3 = c(16L, 2L, 7L, 15L, 14L)
)

df %>% 
  mutate(Total = rowSums(across(starts_with("Race"))),
         across(starts_with("Race"), ~ ./Total, .names = "{.col}_pr"))

#>   Neighborhood Race1 Race2 Race3 Total  Race1_pr   Race2_pr   Race3_pr
#> 1            A    19     1    16    36 0.5277778 0.02777778 0.44444444
#> 2            B    20    17     2    39 0.5128205 0.43589744 0.05128205
#> 3            C    15     2     7    24 0.6250000 0.08333333 0.29166667
#> 4            D    17     4    15    36 0.4722222 0.11111111 0.41666667
#> 5            E    15    20    14    49 0.3061224 0.40816327 0.28571429

关于r - 使用 R 在多个列上迭代操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70268029/

相关文章:

r - 在 ggplotly 中使用 ggplot2 的 sec.axis

c++ - 让 gperftools 与 Rcpp 一起工作

r - 使用 dplyr 过滤相对于另一列中的值的值

r - 在 ggplot2 中的密度图上应用渐变填充

r - 在 R shiny 中,如果我们有 3 个级别的列表,如何自动或基于函数 tabPanel?

r - R打开时打开pdf文件

r - 使用来自 Zoo 的 as.yearmon 修改 ggplot2 中的绘图

r - 如何创建变量(捕获特定阈值的增加)R?

R 中负二项式回归的稳健标准误差与 Stata 中的不匹配

Rmarkdown 和 Shiny 输入