我有一个这样的数据框:
G1 G2 G3 a b f b c a c d b
和参考清单: L: 一个 b C d Ë ˚F
我想得到以下输出:
a: 2, G1,G3 (that is "a" occurs two times in G1 and in G3 column) b: 3, G1,G2,G3 c: 2, G1,G2
等等.. 谁能帮我?很抱歉打扰你,但我是R的新人 提前谢谢。
爱莲
答案 0 :(得分:3)
你可以这样做:
r <- reshape(d,varying=list(colnames(d)),direction='long',
v.names='value',times=colnames(d),timevar='colname')
res <- by(r,r$value,FUN=function(x){unique(x$colname)})
> res
r$value: a
[1] "G1" "G3"
------------------------------------------------------------
r$value: b
[1] "G1" "G2" "G3"
------------------------------------------------------------
r$value: c
[1] "G1" "G2"
------------------------------------------------------------
r$value: d
[1] "G2"
------------------------------------------------------------
r$value: f
[1] "G3"
基本上res
是一个列表,其中包含每个字母,字母出现的列名向量,例如:
res$a : 'G1', 'G3'
res$b : 'G1', 'G2', 'G3'
...
如果您只想要出现的次数,您可以这样做:
> lapply(res,length)
$a
[1] 2
$b
[1] 3
$c
[1] 2
$d
[1] 1
$f
[1] 1
编辑:
要在文件上写res
,可以采用以下方法:
# prepare the table (data.frame) to be written
dF <- do.call(rbind.data.frame, lapply(res,function(x){list(Occur=length(x),Columns=paste(x,collapse=' '))}))
dF <- cbind(Letter=row.names(dF),dF)
# write the table to file
write.table(dF,row.names=FALSE,sep=',',file='myfile.csv')
文件文字:
"Letter","Occur","Columns"
"a",2,"G1 G3"
"b",3,"G1 G2 G3"
"c",2,"G1 G2"
"d",1,"G2"
"f",1,"G3"
答案 1 :(得分:1)
我以另一种方式尝试过这个。
A=data.frame( G1=c("a","b","c"), G2=c("b","c","d"), G3=c("f","a","b"))
B= melt(as.matrix(A))
B$X2 =as.character(B$X2)
B1=table(as.matrix(A))
D=aggregate(X2~value , B, FUN=c)
D$cnt=B1[D$value]
D
输出
value X2 cnt
1 a G1, G3 2
2 b G1, G2, G3 3
3 c G1, G2 2
4 d G2 1
5 f G3 1
答案 2 :(得分:1)
这两种方法都很有效。只是想我会给出一个与我用于类似问题的方法不同的方法。
#Vinux's data:
A=data.frame( G1=c("a","b","c"), G2=c("b","c","d"), G3=c("f","a","b"))
B <- data.frame(x=rep(colnames(A), sapply(A, length)), #means of reshaping data
y=c(apply(A, 2, as.character)))
C <- split(B$x, B$y) #column names by value
D <- data.frame(letter=names(C), occurance=sapply(C, length)) #get occurrences
D$column <- sapply(C, as.character) #force vector of vectors
D[, c(1, 3, 2), ] #order it
哪个收益率:
letter column occurance
a a G1, G3 2
b b G1, G2, G3 3
c c G1, G2 2
d d G2 1
f f G3 1