Separate columns with constant numbers and condense them to one row in R data.frame

后端 未结 4 490
醉酒成梦
醉酒成梦 2020-12-11 13:46

I have a data.frame called d. In this data.frame, some columns consist of constant numbers across the rows of the first column: study.name (see bel

4条回答
  •  孤城傲影
    2020-12-11 14:16

    May be we need

    library(dplyr)
    d %>%
       group_by(study.name) %>%
       slice(1)
    

    Or in base R after grouping by 'study.name', get the first row while specifying the na.action = NULL as the default option is na.omit which can omit any row having NA in any of the columns

    aggregate(.~ study.name, d, head, 1, na.action = NULL)
    

    If we want to subset the columns

    nm1 <- names(which(!colSums(!do.call(rbind, by(d[-1], d$study.name,
         FUN = function(x) lengths(sapply(x, unique)) == 1)))))
    unique(d[c("study.name", nm1)])
    

提交回复
热议问题