在 mutate 和 ifelse 中使用排序变量的名称

Using names of sorted variables within mutate and ifelse

我有以下示例数据:

id <- c(1, 2, 3)
ex3 <- c(0.8,   0.2, 0.3)
ex2 <- c(0.1,   0.4, 0.04)
ex1 <- c(0.04,  0.3, 0.5)
ex <- c(1, 1, 1)
ran <- c(0.5, 0.7, 0.6)
dat <- data.frame(id, ex1, ex2, ex3, ex, ran)

dat

  id  ex1  ex2 ex3 ex ran
1  1 0.04 0.10 0.8  1 0.5
2  2 0.30 0.40 0.2  1 0.7
3  3 0.50 0.04 0.3  1 0.6

我想使用以下代码修改变量“ex” dplyr/tidyr:

library(dplyr)
library(tidyr)

dat %>% 
  pivot_longer(
    cols = ex1:ex3
  ) %>% 
  arrange(id, desc(value)) %>% 
  group_by(id) %>% 
  mutate(ex = ifelse(ran <= value[1] & ran > sum(value[2], value[3]), 5, ex)) %>% 
  pivot_wider(
    names_from=name
  )

# A tibble: 3 x 6
# Groups:   id [3]
     id    ex   ran   ex3   ex2   ex1
  <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
1     1     5   0.5   0.8  0.1   0.04
2     2     1   0.7   0.2  0.4   0.3 
3     3     1   0.6   0.3  0.04  0.5

是否可以在 mutate 的 ifelse 语句中使用名称“ex1”-“ex3”作为“ex”的新值而不是“5”?示例:使用 ex$ 变量的名称作为新值会导致此输出:

  id ex3  ex2  ex1  ex ran
1  1 0.8 0.10 0.04 ex3 0.5
2  2 0.2 0.40 0.30   1 0.7
3  3 0.3 0.04 0.50   1 0.6

或使用 ex$ 变量的数量导致此输出:

  id ex3  ex2  ex1  ex ran
1  1 0.8 0.10 0.04   3 0.5
2  2 0.2 0.40 0.30   1 0.7
3  3 0.3 0.04 0.50   1 0.6

或者如果我想将最低值作为“ex”的新值(因为它是“ex2”):

  id ex3  ex2  ex1  ex ran
1  1 0.8 0.10 0.04   1 0.5
2  2 0.2 0.40 0.30   1 0.7
3  3 0.3 0.04 0.50   1 0.6

总结一下:我想引用排序后的“ex$”值的变量名,以便在 mutate 的 ifelse 中为“ex”创建新值。

一种方法是使用 readr 包中的 parse_number 从 ex1、ex2、ex3 中提取数字。根据您可以执行的逻辑:

parse_number(name[1]) 这里 1 是列中的位置,您可以使用 2 或 3 取决于最适合您的逻辑。

library(dplyr)
library(tidyr)
library(readr)

dat %>% 
  pivot_longer(
    cols = ex1:ex3
  ) %>% 
  arrange(id, desc(value)) %>% 
  group_by(id) %>% 
  mutate(ex = ifelse(ran <= value[1] & ran > sum(value[2], value[3]), parse_number(name[3]), ex)) %>% 
  pivot_wider(
    names_from=name
  )

   id    ex   ran   ex1   ex2   ex3
  <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
1     1     3   0.5   0.8  0.1   0.04
2     2     1   0.7   0.2  0.4   0.3 
3     3     1   0.6   0.3  0.04  0.5 

全名:

mibrary(dplyr)
library(tidyr)
library(readr)

dat %>% 
  pivot_longer(
    cols = ex1:ex3
  ) %>% 
  arrange(id, desc(value)) %>% 
  group_by(id) %>% 
  mutate(ex = ifelse(ran <= value[1] & ran > sum(value[2], value[3]), name[1], as.character(ex))) %>% 
  pivot_wider(
    names_from=name
  )
     id ex      ran   ex1   ex2   ex3
  <dbl> <chr> <dbl> <dbl> <dbl> <dbl>
1     1 ex1     0.5   0.8  0.1   0.04
2     2 1       0.7   0.2  0.4   0.3 
3     3 1       0.6   0.3  0.04  0.5