首页 > 解决方案 > 按因子级别对数据进行分组,然后转换为以 colname 为级别的数据框?

问题描述

有我无法解决的问题:

数据:

df <- data.frame(f1=c("a", "a", "b", "b", "c", "c", "c"), 
                 v1=c(10, 11, 4, 5, 0, 1, 2))

data.frame:f1 is factor
  f1 v1
  a   10
  a   11
  b   4
  b   5
  c   0
  c   1   
  c   2
 # What I want is:(for example, fetch data with the number of element of some level == 2, then to data.frame)
  a   b
 10   4
 11   5  

提前致谢!

标签: rdataframe

解决方案


我可能在这里遗漏了一些简单的东西,但下面使用的方法dplyr有效。

library(dplyr)
nlevels = 2

df1 <- df %>%
        add_count(f1) %>%
        filter(n == nlevels) %>%
        select(-n) %>%
        mutate(rn = row_number()) %>%
        spread(f1, v1) %>%
        select(-rn)

这给

#      a     b
#   <int> <int>
#1    10    NA
#2    11    NA
#3    NA     4
#4    NA     5

现在,如果你想删除NA's 我们可以做

do.call("cbind.data.frame", lapply(df1, function(x) x[!is.na(x)]))

#   a b
#1 10 4
#2 11 5

由于我们过滤了仅具有nlevels观察值的数据框,因此最终数据框中的每一列将具有相同的行数。


推荐阅读