R-根据因子水平计算变量



我是R的新手,并且通常是编程。我目前正在努力进行数据转换的代码,希望有人可以花一点时间帮助我。

在可再现的例子下方:

#    Data
a <- c(rnorm(12, 20))
b <- c(rnorm(12, 25))
f1 <- rep(c("X","Y","Z"), each=4) #family
f2 <- rep(x = c(0,1,50,100), 3) #reference and test levels
dt <- data.frame(f1=factor(f1), f2=factor(f2), a,b)
#library loading
library(tidyverse)

目标:使用参考值计算所有值(ab)。计算应为: a/a_ref a_ref = af2=0取决于家庭时(f1可以是X,Y或Z)。

我尝试使用此代码来解决此问题:

    test <- filter(dt, f2!=0) %>% group_by(f1) %>%
    mutate("a/a_ref"=a/(filter(dt, f2==0) %>% group_by(f1) %>% distinct(a) %>% pull))

我得到:

测试结果

您可以看到aa_ref划分。但是我的脚本似乎回收了参考值的使用(a_ref),而不论家庭f1

您是否有任何建议,因此A是根据家庭计算的(f1)?

谢谢您的阅读!


编辑

我找到了一种"手动"

做的方法
   filter(dt, f1=="X") %>% mutate("a/a_ref"=a/(filter(dt, f1=="X" & f2==0) %>% distinct(a) %>% pull()))
      f1  f2        a        b         a/a_ref
    1  X   0 21.77605 24.53115 1.0000000
    2  X   1 20.17327 24.02512 0.9263973
    3  X  50 19.81482 25.58103 0.9099366
    4  X 100 19.90205 24.66322 0.9139422

问题是我必须更新每个变量和家庭的代码,因此不是一种干净的方法。

# use this to reproduce the same dataset and results
set.seed(5)
# Data
a <- c(rnorm(12, 20))
b <- c(rnorm(12, 25))
f1 <- rep(c("X","Y","Z"), each=4) #family
f2 <- rep(x = c(0,1,50,100), 3) #reference and test levels
dt <- data.frame(f1=factor(f1), f2=factor(f2), a,b)
#library loading
library(tidyverse)
dt %>%
  group_by(f1) %>%                 # for each f1 value
  mutate(a_ref = a[f2 == 0],       # get the a_ref and add it in each row
         "a/a_ref" = a/a_ref) %>%  # divide a and a_ref
  ungroup() %>%                    # forget the grouping
  filter(f2 != 0)                  # remove rows where f2 == 0
# # A tibble: 9 x 6
#       f1     f2        a        b    a_ref `a/a_ref`
#   <fctr> <fctr>    <dbl>    <dbl>    <dbl>     <dbl>
# 1      X      1 21.38436 24.84247 19.15914 1.1161437
# 2      X     50 18.74451 23.92824 19.15914 0.9783583
# 3      X    100 20.07014 24.86101 19.15914 1.0475490
# 4      Y      1 19.39709 22.81603 21.71144 0.8934042
# 5      Y     50 19.52783 25.24082 21.71144 0.8994260
# 6      Y    100 19.36463 24.74064 21.71144 0.8919090
# 7      Z      1 20.13811 25.94187 19.71423 1.0215013
# 8      Z     50 21.22763 26.46796 19.71423 1.0767671
# 9      Z    100 19.19822 25.70676 19.71423 0.9738257

您可以使用以上的变量来执行此操作:

dt %>% 
  group_by(f1) %>% 
  mutate_at(vars(a:b), funs(./.[f2 == 0])) %>% 
  ungroup() 

或通常使用vars(a:z)使用az之间的所有变量,只要它们是数据集中的一个变量。

另一种解决方案可以使用mutate_if,例如:

dt %>% 
  group_by(f1) %>% 
  mutate_if(is.numeric, funs(./.[f2 == 0])) %>% 
  ungroup()

将函数应用于您拥有的所有数字变量。变量f1f2将是因子变量,因此它仅排除这些变量。

最新更新