在大数据框架中的行连接

时间:2013-05-06 19:45:16

标签: r

我有一个简单的问题。我必须分析的data.frame看起来像这样:

 a     o    34   c    456    d    32   r    21
 a     s    21   f    78     
 s     z    21   df    4     m    21        
 t     x    2    vb   20     p    34   q    56   g   65
 d     n    78   oi   43     w   322   y    123
 d     q    76   gh   0.9    wt   3

我只想要以下输出:

 a     o    34   c    456    d    32   r    21  s 21  f 78  
 s     z    21   df    4     m    21        
 t     x    2    vb   20     p    34   q   56   g 65
 d     n    78   oi   43     w   322   y   123  q 76  gh   0.9    wt   3

换句话说,复制以“a”开头的行,因此名为“a”的第二行将附加到名为“a”的第一行,而不管单词或数字的顺序(升序或降序)。与“d”相同。我尝试使用函数“table”来考虑“a”,“s”,“t”,“d”的频率,但是因为我是R的新手,所以在考虑频率后我无法继续。

  

dput(head(tmp1))

输出:

structure(list(V1 = structure(c(38L, 37L, 14L, 26L, 35L, 9L), .Label = c("AATF", 
"C14orf143", "CCDC57", "CLNS1A", "DSCC1", "ENOPH1", "EXOSC2", 
"FARSA", "FASN", "FKBP4", "FTSJ3", "GUF1", "HSPA4", "HSPA9", 
"IFRD2", "LARP4", "MAZ", "MECR", "NARS2", "NAT10", "NFS1", "NLE1", 
"NUP107", "PLA2G12A", "POLD2", "POLR3K", "PPP5C", "PSME3", "RAE1", 
"RET", "RNF126", "SFXN1", "SLC24A3", "SLC25A15", "THOP1", "TIMM13", 
"TMEM93", "TP53I11", "TRAP1", "WDR18", "WDR61"), class = "factor"), 
    V2 = structure(c(24L, 21L, 14L, 25L, 27L, 26L),.......), row.names = c(NA, 6L), class = "data.frame")

1 个答案:

答案 0 :(得分:2)

options(stringsAsFactors=FALSE)

DF <- read.delim(text=" a     o    34   c    456    d    32   r    21
 a     s    21   f    78     
 s     z    21   df    4     m    21        
 t     x    2    vb   20     p    34   q    56   g   65
 d     n    78   oi   43     w   322   y    123
 d     q    76   gh   0.9    wt   3",fill=TRUE,sep=" ",header=FALSE)



library(plyr)

dlply(DF,.(V2),function(x) { 
  res <- as.character(na.omit(do.call(c,as.data.frame(t(x[,-2])))))
  res <- res[res!=""]
  res
                             })

$a
 [1] "o"   "34"  "c"   "456" "d"   "32"  "r"   "21"  "s"   "21"  "f"   " 78"

$d
 [1] "n"    "78"   "oi"   "43.0" "w"    "322"  "y"    "123"  "q"    "76"   "gh"   " 0.9"
[13] "wt"   " 3"  

$s
[1] "z"  "21" "df" "4"  "m"  "21"

$t
 [1] "x"  "2"  "vb" "20" "p"  "34" "q"  "56" "g"  "65"