我有一个这样的数据框:
G1 G2 G3 a b f b c a c d b
和参考列表: L: a b c d e 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 的新手,提前谢谢。
埃莱奥诺拉
我有一个这样的数据框:
G1 G2 G3 a b f b c a c d b
和参考列表: L: a b c d e 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 的新手,提前谢谢。
埃莱奥诺拉
你可以这样做:
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"
我以另一种方式尝试过。
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
这两种方法都已经很好地工作了。只是想我会给出一些不同的方法来解决类似的问题。
#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