首页 > 解决方案 > 如何将行中的每个元素除以相应的行值?

问题描述

(我想将一行中的每个元素除以相应的行值。当存在行元素时,分母应该是“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)

标签: r

解决方案


您的数据:

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

推荐阅读