代码之家  ›  专栏  ›  技术社区  ›  Hamideh

基于与特定列的比较在R tidyverse中创建大量列

  •  1
  • Hamideh  · 技术社区  · 1 年前

    我在R tidyverse中有一个数据集,我想根据与sp列的比较创建192列,就像mp_comp_1列一样。我如何为tidyverse的192列完成此操作?

    library(tidyverse)    
    
    df <- data.frame(matrix(ncol = 4, nrow = 3))
    
    df%>%
      mutate(sp = c(34.9, 34.3, 34.4)) %>%
      mutate(mp_1 = c(35, 32.1, 34.4)) %>%
      mutate(mp_2 = c(30, 38.1, 39.4)) %>%
      mutate(mp_192 = c(34.9, 34.3, 30.4)) %>%
      select(sp, mp_1, mp_2, mp_192) %>%
      mutate(mp_comp_1= if_else(mp_1>sp, "bigger",
                                if_else(mp_1<sp, "smaller", "equal")))
    

    enter image description here

    1 回复  |  直到 1 年前
        1
  •  2
  •   benson23    1 年前

    你可以利用 across case_when .

    library(dplyr)
    
    df |> 
      mutate(across(starts_with("mp_"),
                    ~case_when(.x > sp ~ "bigger",
                               .x < sp ~ "smaller",
                               .x == sp ~ "equal"),
                    .names = "{.col}_comp"))
    
        sp mp_1 mp_2 mp_192 mp_1_comp mp_2_comp mp_192_comp
    1 34.9 35.0 30.0   34.9    bigger   smaller       equal
    2 34.3 32.1 38.1   34.3   smaller    bigger       equal
    3 34.4 34.4 39.4   30.4     equal    bigger     smaller
    

    数据

    df <- structure(list(sp = c(34.9, 34.3, 34.4), mp_1 = c(35, 32.1, 34.4
    ), mp_2 = c(30, 38.1, 39.4), mp_192 = c(34.9, 34.3, 30.4)), class = "data.frame", row.names = c(NA, 
    -3L))
    
    推荐文章