r - 根据另一列的值强制不同的值相等
问题描述
我知道标题可能令人困惑,我可能很难解释。我想在第一列中获取具有重复值的数据框,并将不同列中的值更改为与第一列中的重复值相同。那么我可以调用 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 循环,但我不确定如何强制第一列中所有相等的值的第二列值。关于如何解决这个问题的任何建议。谢谢!
解决方案
我们可以按“用户”分组,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)
推荐阅读
- ruby-on-rails - nginx代理rails重写代理资产
- lisp - 在 Common Lisp 中为字符串交替大写/小写
- hover - 如何在情节子图中悬停标签中设置小数位?
- winapi - 预览处理程序 dll 权限问题
- docker - docker-users 组在重新启动或从 VM Docker 桌面注销时被删除
- spring-boot - Vaadin 7 是否与 Spring Boot 2.x 兼容?
- python - 如何添加循环几次的所有随机生成的数字
- javascript - 试图将一串javascript文件数据转换为我可以显示的美化代码
网站上的html标签
- c# - 无重复的随机数生成器
- python-3.x - 使用 SPACY 查找匹配的公司名称