Putting rowwise counts of value occurences into new variables, how to do that in R with dplyr?

后端 未结 3 1112
轻奢々
轻奢々 2020-12-20 06:55

I have a large dataframe (df) that looks like this:

structure(list(var1 = c(1, 2, 3, 4, 2, 3, 4, 3, 2), var2 = c(2, 
3, 4, 1, 2, 1, 1, 1, 3), var3 = c(4, 4,          


        
3条回答
  •  盖世英雄少女心
    2020-12-20 07:43

    This uses rowwise() and do() from dplyr but it's definitely ugly.

    Not sure if there is something that can modify from this so that you get a data.frame output directly as shown over @ https://github.com/hadley/dplyr/releases.

    interim_res <- df %>% 
                      rowwise() %>% 
                      do(out = sapply(min(df):max(df), function(i) sum(i==.)))
    
    interim_res <- interim_res[[1]] %>% do.call(rbind,.) %>% as.data.frame(.)
    

    Then to get intended result:

    res <- cbind(df,interim_res)
    

提交回复
热议问题