我怎样才能根据几个栏目进行分类

时间:2018-05-23 19:00:09

标签: r

我有这样的数据

$(".grid_home").mouseenter(function(){

    var $grid_home = $(this),
        $first = $grid_home.find(".grid_home_inside" ).first(),
        $last = $grid_home.find(".grid_home_inside" ).last(),
        $displayed = $grid_home.find(".displayed"),
        $next = $displayed.next('.grid_home_inside'),
        $prev = $next.prev(".grid_home_inside");

    if( $next.length == 0 ) {

        $first.addClass("displayed");
        $last.removeClass("displayed");

    } else {

        $next.addClass("displayed");
        $prev.removeClass("displayed");

    }

});

我试图根据两栏

对它们进行分类

我可以做以下

df<- structure(list(V1 = structure(c(10L, 4L, 7L, 5L, 3L, 1L, 8L, 
11L, 12L, 9L, 2L, 6L), .Label = c("BRA_AC_A6IX", "BRA_BH_A18F", 
"BRA_BH_A18V", "BRA_BH_A1ES", "BRA_BH_A1FE", "BRA_BH_A6R8", "BRA_E2_A15A", 
"BRA_E2_A15K", "BRA_E2_A1B4", "BRA_EM_A15E", "BRA_LQ_A4E4", "BRA_OK_A5Q2"
), class = "factor"), V2 = structure(c(2L, 3L, 5L, 3L, 3L, 5L, 
3L, 4L, 1L, 4L, 2L, 2L), .Label = c("Level ii", "Level iia", 
"Level iib", "Level iiia", "Level iiic"), class = "factor"), 
    V3 = structure(c(1L, 1L, 1L, 2L, 2L, 2L, 3L, 3L, 3L, 3L, 
    3L, 4L), .Label = c("amira", "boro", "car", "dim"), class = "factor")), class = "data.frame", row.names = c(NA, 
-12L))

但我希望有这样的输出

library(dplyr)
df %>% 
+   group_by(V2) %>%
+   summarise(no_rows = length(V2))
# A tibble: 5 x 2
  V2         no_rows
  <fct>        <int>
1 Level ii         1
2 Level iia        3
3 Level iib        4
4 Level iiia       2
5 Level iiic       2

2 个答案:

答案 0 :(得分:0)

怎么样

library(reshape2)
df1 <- df[,-1]
table(melt(df1, id.var="V2")[-2])

答案 1 :(得分:0)

这是tidyverse方法。我估计你真的想要计数,但如果你只想要容易添加的存在/缺席。

df <- structure(list(V1 = structure(c(10L, 4L, 7L, 5L, 3L, 1L, 8L, 11L, 12L, 9L, 2L, 6L), .Label = c("BRA_AC_A6IX", "BRA_BH_A18F", "BRA_BH_A18V", "BRA_BH_A1ES", "BRA_BH_A1FE", "BRA_BH_A6R8", "BRA_E2_A15A", "BRA_E2_A15K", "BRA_E2_A1B4", "BRA_EM_A15E", "BRA_LQ_A4E4", "BRA_OK_A5Q2"), class = "factor"), V2 = structure(c(2L, 3L, 5L, 3L, 3L, 5L, 3L, 4L, 1L, 4L, 2L, 2L), .Label = c("Level ii", "Level iia", "Level iib", "Level iiia", "Level iiic"), class = "factor"), V3 = structure(c(1L, 1L, 1L, 2L, 2L, 2L, 3L, 3L, 3L, 3L, 3L, 4L), .Label = c("amira", "boro", "car", "dim"), class = "factor")), class = "data.frame", row.names = c(NA, -12L))

library(tidyverse)
df %>%
  select(-V1) %>%
  count(V2, V3) %>%
  spread(V3, n, fill = 0L)
#> # A tibble: 5 x 5
#>   V2         amira  boro   car   dim
#>   <fct>      <int> <int> <int> <int>
#> 1 Level ii       0     0     1     0
#> 2 Level iia      1     0     1     1
#> 3 Level iib      1     2     1     0
#> 4 Level iiia     0     0     2     0
#> 5 Level iiic     1     1     0     0

reprex package(v0.2.0)创建于2018-05-23。