从R中的较大数据帧动态写入文本文件

时间:2016-10-21 17:19:24

标签: r dataframe

我的数据框看起来像这样:

df<-rbind(c(1,0,1,0,1,NA),c(1,0,0,1,1,NA),c(1,0,0,0,0,NA),c(1,1,1,1,1,NA),c( 2,0,1,1,1,1),c(2,1,1,0,0,0),c(2,0,0,0,0,1),c(2,1,1,1,1,1),c(2,0,0,0,0,0))
colnames(df)<-c("Team","A","B","C","D","E")
print(df)

Team    A    B    C    D    E
 1      0    1    0    1    NA
 1      0    0    1    1    NA
 1      0    0    0    0    NA
 1      1    1    1    1    NA
 2      0    1    1    1    1
 2      1    1    0    0    0
 2      0    0    0    0    1
 2      1    1    1    1    1
 2      0    0    0    0    0

我想将每个团队结果动态地写为文本文件,其中每个文件的名称对应于团队编号,并且没有NA编写(每个文件仅包含其各自的0和1。这样最终结果看起来如此像

"1.txt"
 0    1    0    1 
 0    0    1    1 
 0    0    0    0 
 1    1    1    1
"2.txt"
 0    1    1    1    1
 1    1    0    0    0
 0    0    0    0    1
 1    1    1    1    1
 0    0    0    0    0

谢谢!

2 个答案:

答案 0 :(得分:1)

尝试以下操作(dfdata.frame

df<- as.data.frame(rbind(c(1,0,1,0,1,NA),c(1,0,0,1,1,NA),c(1,0,0,0,0,NA),c(1,1,1,1,1,NA),c( 2,0,1,1,1,1),c(2,1,1,0,0,0),c(2,0,0,0,0,1),c(2,1,1,1,1,1),c(2,0,0,0,0,0)))
colnames(df)<-c("Team","A","B","C","D","E")

out <- split(df , f = df$Team)
n_teams <- length(unique(df$Team))
for (i in 1:n_teams) {
  eval(parse(text = paste0("write.table(out[[", i, "]], \"C:/Test/", i, ".txt\", sep=\"\t\",row.names=FALSE)")))
}

如果你发布可复制的数据,我可以进一步帮助你...

答案 1 :(得分:1)

by函数对此有用,它按因子级别分割data.frame并将函数应用于每个组(请参阅?by)。

在你的情况下,你可以使用类似的东西:

by(df, df$Team, function(x)
  write.table(x, sep = "\t", file = paste0(unique(x$Team), ".txt")))

根据评论扩大:

by(df, df$Team, function(x){

  # drop columns if all are NA
  subset <- x[,colSums(is.na(x)) < nrow(x)]

  # drop team column and write groups to individual files
  write.table(subset[,-1], sep = "\t", 
    file = paste0(unique(x$Team), ".txt"),
    col.names = FALSE, row.names = FALSE)

  })