首页 > 解决方案 > 根据另一列的值强制不同的值相等

问题描述

我知道标题可能令人困惑,我可能很难解释。我想在第一列中获取具有重复值的数据框,并将不同列中的值更改为与第一列中的重复值相同。那么我可以调用 unique() 来减少表格。

例如:

rawdata<- data.frame(User=c('JSmith','JSmith','JDoe','JDoe','MDog','MDog','MDog') ,
                       Visit=c('Y','N','N','N','Y','N','Y'))
#displayed as  
   User    Visit
1 JSmith     Y
2 JSmith     N
3   JDoe     N
4   JDoe     N
5   MDog     Y
6   MDog     N
7   MDog     Y

#I would like to test the visit column for Y and if that is true for user's of the same name, 
#coerce that visit value to Y as well

 User    Visit
1 JSmith     Y
2 JSmith     Y
3   JDoe     N
4   JDoe     N
5   MDog     Y
6   MDog     Y
7   MDog     Y

#That way when I call unique(rawdata[,1]), it should output
 User    Visit
1 JSmith     Y
2   JDoe     N
3   MDog     Y

我使用这个简化的示例将原理应用于更大、更复杂的数据集,但原理是相同的。不幸的是,我不知道从哪里开始。我正在考虑一个带有 if 语句的 for 循环,但我不确定如何强制第一列中所有相等的值的第二列值。关于如何解决这个问题的任何建议。谢谢!

标签: rdataframefor-loopif-statement

解决方案


我们可以按“用户”分组,if有任何“Y”,然后将“访问”更改为“Y”,然后获取distinct

library(dplyr)
rawdata %>% 
    group_by(User) %>% 
    mutate(Visit = if('Y' %in% Visit) 'Y' else 'N') %>%
    ungroup %>%
    distinct
# A tibble: 3 x 2
#  User   Visit
#  <fct>  <chr>
#1 JSmith Y    
#2 JDoe   N    
#3 MDog   Y

如果我们只需要中间输出,那么group_by/mutate只需要上一步中的


或者另一种选择是summarise在做一个小组之后

rawdata %>%
   group_by(User) %>% 
   summarise(Visit = Visit[match('Y', Visit, nomatch = 1)])

或者我们可以arrange数据集然后做一个distinct

rawdata %>%
    arrange(User, Visit == 'N') %>% 
    distinct(User, .keep_all = TRUE)

推荐阅读