【问题标题】:Concatenate multiple copies of a variable into one variable with a large dataset in R将一个变量的多个副本连接成一个带有 R 中大型数据集的变量
【发布时间】:2020-06-30 21:43:33
【问题描述】:

我有一个数据集,其中每个变量都有多个版本。所有变量都以 _1、_2、_3 结尾。我想将变量的各种版本连接到一个新列中。我有一个非常大的数据集,所以我想尽量避免手动编码每个变量(例如 dat$test

test_1  test_2  test_3  type_1  type_2  type_3  other_1  other_2  other_3
a        f        f        d     s        t       j         y      b  
s        d        c        v     s        y       h         a      m 
d        s        v        d     h        u       n         j      k  

我希望将变量表示在一个列中,如下所示:

   test    type    other
    aff     dst     jyb
    sdc     vsy     ham
    dsv     dhu     njk

我不熟悉循环,但我认为查找变量名然后将后续版本连接到新列中会涉及到 grep()?有没有人有建议去解决这个问题?任何帮助表示赞赏!

【问题讨论】:

    标签: r loops variables concatenation


    【解决方案1】:

    我们可以将meltdata.tablepaste元素一起使用

    library(data.table)
    melt(setDT(df1, keep.rownames = TRUE), measure  =
          patterns('^test', 'type', 'other'),
        value.name = c('test', 'type', 'other'))[, 
           variable := NULL][, lapply(.SD, paste, collapse=""),
          .(rn)][, rn := NULL][]
    #    test type other
    #1:  aff  dst   jyb
    #2:  sdc  vsy   ham
    #3:  dsv  dhu   njk
    

    或者在tidyverse中使用类似的方法

    library(dplyr)
    library(tidyr)
    library(stringr)
    df1 %>%
       mutate(rn = row_number()) %>%
       pivot_longer(cols = -rn,  names_to = c( ".value", 'grp'), names_sep="_") %>% 
       group_by(rn) %>%
       summarise_at(vars(test:other), str_c, collapse ="") %>%
       select(-rn)
    # A tibble: 3 x 3
    #  test  type  other
    #  <chr> <chr> <chr>
    #1 aff   dst   jyb  
    #2 sdc   vsy   ham  
    #3 dsv   dhu   njk  
    

    数据

    df1 <- structure(list(test_1 = c("a", "s", "d"), test_2 = c("f", "d", 
    "s"), test_3 = c("f", "c", "v"), type_1 = c("d", "v", "d"), type_2 = c("s", 
    "s", "h"), type_3 = c("t", "y", "u"), other_1 = c("j", "h", "n"
    ), other_2 = c("y", "a", "j"), other_3 = c("b", "m", "k")),
       class = "data.frame", row.names = c(NA, 
    -3L))
    

    【讨论】:

      猜你喜欢
      • 2017-02-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-03-13
      相关资源
      最近更新 更多