嗨,我是新来的r,我有一个问题,即从一个名为w2的数据帧中找到用户网络(uID)和文章网络(faID),如
faID uID
1 1256
1 54789
1 547821
2 3258
2 4521
2 4528
3 98745
3 1256
3 3258
3 2145
这只是一个例子,我有超过2000篇文章,我想在用户之间建立一个基于文章的数据框架格式的关系,例如。##为第一条##
1258 54789
1258 547821
54789 547821
##同样适用于第二条##
3258 4521
3258 4528
4528 4521
其他一些信息
dput(头(w2,))结构(列表(费德山口= c (1 l, 1 l, 1 l, 1 l, 1 l, 1 l), uID = c (20909 l, 6661 l、1591 l、28065 l、42783 l、3113 l)), . name = c("起"、"uID"),row.names = c (7 l, 9 l 10 l, 12 l, 14 l, 16 l),类= data.frame")
dim(w2)
[1] 364323 2
我正在使用一位志愿者建议的代码
错误出现在<<<>>" error in UseMethod("regroup"):
没有适用于类"c('integer', 'numeric')"对象的'regroup'方法##
library(dplyr)
edges<-tbl_df(w2) %>%
group_by(w2$faID) %>%
do({
tmp <-combn(sort(.$user),m =2)
data.frame(a=tmp[1,],b=tmp[2,],stringsAsFactors=FALSE )
})%>%
ungroup
}
我想这还没有在dplyr
中实现,从阅读分配名称到dplyr做操作的列表输出
你可以这样做:
library(gsubfn)
library(dplyr)
w2%>%
group_by(faID) %>%
fn$do2(~combn(.$uID, m=2)) #`do2` from the link
# $`1`
# [,1] [,2] [,3]
#[1,] 1256 1256 54789
#[2,] 54789 547821 547821
# $`2`
# [,1] [,2] [,3]
# [1,] 3258 3258 4521
#[2,] 4521 4528 4528
# $`3`
# [,1] [,2] [,3] [,4] [,5] [,6]
# [1,] 98745 98745 98745 1256 1256 3258
# [2,] 1256 3258 2145 3258 2145 2145
数据w2 <- structure(list(faID = c(1L, 1L, 1L, 2L, 2L, 2L, 3L, 3L, 3L, 3L
), uID = c(1256L, 54789L, 547821L, 3258L, 4521L, 4528L, 98745L,
1256L, 3258L, 2145L)), .Names = c("faID", "uID"), class = "data.frame", row.names = c(NA,
-10L))
更新可以这样做:
res <- w2 %>%
group_by(faID) %>%
do({data.frame(
combN=paste(apply(combn(sort(.$uID), m=2),2,paste,collapse=" "),
collapse=", "), stringsAsFactors=F)})
res
# faID combN
# 1 1 1256 54789, 1256 547821, 54789 547821
# 2 2 3258 4521, 3258 4528, 4521 4528
# 3 3 1256 2145, 1256 3258, 1256 98745, 2145 3258, 2145 98745, 3258 98745
library(data.table)
使用cSplit
from https://gist.github.com/mrdwab/11380733
cSplit(cSplit(res, "combN", ", ", "long"),"combN", " ")
# faID combN_1 combN_2
# 1: 1 1256 54789
# 2: 1 1256 547821
# 3: 1 54789 547821
# 4: 2 3258 4521
# 5: 2 3258 4528
# 6: 2 4521 4528
# 7: 3 1256 2145
# 8: 3 1256 3258
# 9: 3 1256 98745
# 10: 3 2145 3258
# 11: 3 2145 98745
# 12: 3 3258 98745