r - 如何将行中的每个元素除以相应的行值?
问题描述
(我想将一行中的每个元素除以相应的行值。当存在行元素时,分母应该是“Ac”的值。
Ac V1 V2 V3 V4 V5 V6 V7
6.6 NA NA NA NA 0 5.6 5.2
8.4 NA 0 82.5 31 0 0 1.1
Output:
V1 V2 V3 V4 V5 V6 V7
NA 0/8.4 82.5/8.4 31/8.4 (0*6.6+0*6.6)/(6.6+8.4) (5.6*6.6+0*8.4)/(6.6+8.4) (5.2*6.6+1.1*8.4)/(6.6+8.4)
解决方案
您的数据:
library(dplyr)
df <- data.frame(V1 = c(rep(NA,4), 0, 5.6, 5.2),
V2 = c(NA, 0 , 82.5, 31, 0, 0, 1.1))
df <- df %>%
t %>% as.data.frame() %>%
dplyr::mutate(Ac = c(6.6, 8.4)) %>%
dplyr::select(Ac, V1:V7)
df
> df
Ac V1 V2 V3 V4 V5 V6 V7
1 6.6 NA NA NA NA 0 5.6 5.2
2 8.4 NA 0 82.5 31 0 0.0 1.1
- 答案:
resp <- df %>%
dplyr::select(-Ac) %>%
t %>% as.data.frame() %>%
dplyr::mutate(V1_1 = V1/df[1,1],
V2_2 = V2/df[2,1]) %>%
dplyr::rowwise() %>%
dplyr::mutate(resp = ifelse(is.na(V1_1) & is.na(V2_2), NA,
sum(V1_1, V2_2, na.rm = T))) %>%
dplyr::select(resp) %>% t %>% as.data.frame()
resp
> resp
V1 V2 V3 V4 V5 V6 V7
resp NA 0 9.821429 3.690476 0 0.8484848 0.9188312
推荐阅读
- selenium - 如何使用 Katalon Studio 处理浏览器级别的通知
- amazon-web-services - Amazon SES 向电子邮件列表中的收件人发送重复的电子邮件
- javascript - IntersectionObserver + 滚动事件监听器
- flutter - Flutter:如何在运行 JavaScript 函数并显示 html 后等待 WebView 完成加载?
- image - 有什么办法可以解决这个警告吗?
- php - 发布大数据时我的 PHP 文件未执行
- laravel - Laravel:无法选择要上传的多个图像
- javascript - Express 服务器不在我的主机上提供静态文件
- apache-kafka - Flink 减少 shuffle 开销和内存消耗
- javascript - 材质表和工具提示上的 ExpressionChangedAfterItHasBeenCheckedError