r - 按列值对 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_3
且Totl_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
解决方案
我只是将所有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_2
和Totl_3
。
推荐阅读
- vba - 仅将记录返回到标记为 0 或 1 的报告
- hadoop - 强制 HiveServer2 运行 MapReduce 作业
- sql - SQL - 插入两列,一列来自表,另一列是常量
- java - 这个java函数有什么作用?
- react-native - Parse.User.currentAsync() 返回 null
- lotus-domino - lotusscript 代理调用另一个 lotusscript 代理不工作
- python - 我在 python 编码中遇到缩进问题,但我无法找到确切的问题来解决它
- java - 为什么插入时没有设置多对一关系的外键字段?
- php - 在 PHP MySQL 中,根据搜索结果求和总行数
- excel - 从描述中提取计数的方法