首页 > 解决方案 > 按列值对 DF 的所有行应用数学计算

问题描述

我想应用一个数学计算(Occ_1+1)/(Totl_1+Unique_words)(Occ_2+1)/(Totl_2+Unique_words)(Occ_3+1)/(Totl_3+Unique_words)创建一个新列作为Probability_1, Probability_2,Probability_3

现在我正在单独进行每项计算并将它们组合在一起。

例如:因为(Occ_1+1)我正在做sapply(df$Occ_1, function(x){x+1})

我几乎有50 Occ_50 Totl_所以如果我单独进行所有计算,我的代码会变得很长。
有没有办法一次做所有的计算。

采样DF直到Occ_3Totl_3

 word        Occ_1  Occ_2  Occ_3  Totl_1 Totl_2 Totl_3 Unique_words
  <chr>      <int>  <int>  <int>  <int>  <int>  <int>        <int>
 1 car          0     1     0     11      9      7           17
 2 saturn       2     0     2     11      9      7           17
 3 survival     1     2     0     11      9      7           17
 4 baseball     1     1     0     11      9      7           17
 5 color        0     0     1     11      9      7           17
 6 muscle       0     1     0     11      9      7           17

标签: rdplyrtidyversetidyrtidytext

解决方案


我只是将所有Occ..,Tot..列收集在一起并执行所需的算术

occ_cols <- grep("^Occ", names(df))
tot_cols <- grep("^Totl", names(df))

df[paste0("Probability_", 1:length(occ_cols))] <- 
      (df[occ_cols] + 1)/(df[tot_cols] + df$Unique_words)

df
#      word Occ_1 Occ_2 Occ_3 Totl_1 Totl_2 Totl_3 Unique_words Probability_1
#1      car     0     1     0     11      9      7           17    0.03571429
#2   saturn     2     0     2     11      9      7           17    0.10714286
#3 survival     1     2     0     11      9      7           17    0.07142857
#4 baseball     1     1     0     11      9      7           17    0.07142857
#5    color     0     0     1     11      9      7           17    0.03571429
#6   muscle     0     1     0     11      9      7           17    0.03571429

#  Probability_2 Probability_3
#1    0.07692308    0.04166667
#2    0.03846154    0.12500000
#3    0.11538462    0.04166667
#4    0.07692308    0.04166667
#5    0.03846154    0.08333333
#6    0.07692308    0.04166667

但是,请确保所有列Occ..Tot..列的顺序相同。对于此示例,我们有Occ_1, Occ_2,Occ_3后跟Totl_1,Totl_2Totl_3


推荐阅读