r - 将两对列合并为具有唯一值的两列
问题描述
我有下面的数据框:
from<-c("Jack","Bill","Jack","Adam")
to<-c("Lary","Jack","Tom","Lary")
from_group<-c("A","A","A","C")
to_group<-c("B","A","D","B")
A<-data.frame(from,to,from_group,to_group)
from to from_group to_group
1 Jack Lary A B
2 Bill Jack A A
3 Jack Tom A D
4 Adam Lary C B
我想将前两列合并为具有所有唯一名称的一列,将后两列合并为另一列,其中包含所有相关组,例如:
names groups
1 Jack A
2 Bill A
3 Adam C
4 Lary B
5 Tom D
解决方案
你可以unique
使用unlist
unique(data.frame(names=unlist(A[1:2]), groups=unlist(A[3:4])))
# names groups
#from1 Jack A
#from2 Bill A
#from4 Adam C
#to1 Lary B
#to3 Tom D
或没有行名:
unique(data.frame(names=unlist(A[1:2], use.names = FALSE),
groups=unlist(A[3:4], use.names = FALSE)))
# names groups
#1 Jack A
#2 Bill A
#4 Adam C
#5 Lary B
#7 Tom D
或使用名称
i <- endsWith(names(A), "_group")
unique(data.frame(names=unlist(A[!i]), groups=unlist(A[i])))
推荐阅读
- python - Django 是否为分页器功能获取所有数据库对象并使其效率低下?
- html - 如何获取输入的日期值?
- php - OctoberCMS:管理双向多对多关系
- python - 将一个函数的值传递给另一个函数
- http - nginx http 到 https 重定向
- java - 如何在 selenium java 中处理 Outlook/Windows 实时邮件
- python - GUI Tkinter 中的 TypeError:ask_stableLvl() 缺少 1 个必需的位置参数:“输入”
- amazon-web-services - 使用 aws codebuild 未收到有关 bitbucket 拉取请求的 Sonar 评论
- javascript - 等待一个不返回承诺的异步方法被明确认为是一种不好的做法?
- php - php插入数据库函数然后在另一个函数错误中全选