r合并某些值优先于其他值的行 [英] R combine rows where certain value overrules other values
本文介绍了r合并某些值优先于其他值的行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个数据框,如下所示。我想根据Person列中的重复项合并行。但是,对于指定的列(本例中为Beer、Cola、Wodka),某个值(本例中为1)是否可能优先于其他值(本例中为0)。
当前数据帧:
person <- c("John", "John", "Alex", "Nicole", "Nicole")
Sex <- c("M","M","W", "W", "W")
Beer <- c(1,1,1,1,0)
Cola <- c(0,1,0,0,0)
Wodka <- c(0,1,0,0,1)
df <- data.frame(person,Sex,Beer,Cola,Wodka)
结果应为:
person <- c("John", "Alex", "Nicole")
Sex <- c("M", "W", "W")
Beer <- c(1,1,1)
Cola <- c(1,0,0)
Wodka <- c(1,0,1)
df <- data.frame(person,Sex,Beer,Cola,Wodka)
谢谢。
推荐答案
使用dplyr,您可以summarise()
获得每人一行,并
指定列的最大值:
library(tidyverse)
person <- c("John", "John", "Alex", "Nicole", "Nicole")
Sex <- c("M", "M", "W", "W", "W")
Beer <- c(1, 1, 1, 1, 0)
Cola <- c(0, 1, 0, 0, 0)
Wodka <- c(0, 1, 0, 0, 1)
df <- data.frame(person, Sex, Beer, Cola, Wodka)
df %>%
group_by(person, Sex) %>%
summarise(across(c(Beer, Cola, Wodka), max))
#> `summarise()` regrouping output by 'person' (override with `.groups` argument)
#> # A tibble: 3 x 5
#> # Groups: person [3]
#> person Sex Beer Cola Wodka
#> <chr> <chr> <dbl> <dbl> <dbl>
#> 1 Alex W 1 0 0
#> 2 John M 1 1 1
#> 3 Nicole W 1 0 1
这篇关于r合并某些值优先于其他值的行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文