对数据框进行计算(将每个单元格除以数据框中的最后一行并计算内容)

时间:2017-10-10 12:35:23

标签: r dataframe dplyr

我在数据框中进行计算时遇到问题。 我有这个等式:

  

Q =(FL_18 / Control(FL_18列))*(Control / Abs_18(Abs_18列))

我的数据:

df <- structure(list(Layout = c("SM1_1", "SM1_2", "SM1_3", "SM1_4", 
"SM1_5", "Control"), Abs_18_mean = c(0.02753575, 0.04619625, 
0.04429875, 0.0485425, 0.033855, 0.062293375), FL_18_mean = c(2815.5, 
3330.25, 3375.375, 4458.5, 4905.5, 769.75)), .Names = c("Layout", 
"Abs_18_mean", "FL_18_mean"), row.names = c(NA, -6L), class = c("tbl_df", 
"tbl", "data.frame"))

我想在dplyr中这样做,有可能吗?

1 个答案:

答案 0 :(得分:2)

您可以尝试:

df %>% 
  group_by(Layout) %>% 
  mutate(Q=.$FL_18_mean[6]/FL_18_mean*Abs_18_mean/.$Abs_18_mean[6])
  # or a more general solution:
  # mutate(Q=.$FL_18_mean[.$Layout == "Control"]/FL_18_mean*Abs_18_mean/.$Abs_18_mean[.$Layout == "Control"])
# A tibble: 6 x 4
# Groups:   Layout [6]
   Layout Abs_18_mean FL_18_mean          Q
    <chr>       <dbl>      <dbl>      <dbl>
1   SM1_1  0.02753575   2815.500 0.12085071
2   SM1_2  0.04619625   3330.250 0.17141062
3   SM1_3  0.04429875   3375.375 0.16217252
4   SM1_4  0.04854250   4458.500 0.13453683
5   SM1_5  0.03385500   4905.500 0.08528004
6 Control  0.06229337    769.750 1.00000000