【问题标题】:how to split a dataframe in to separate dataframe based on the number of columns如何根据列数将数据框拆分为单独的数据框
【发布时间】:2015-11-14 11:29:01
【问题描述】:

我有一个数据框,我试图将数据框拆分为单独的数据集,并将数据集的文件名作为数据框的 colnames

df1 <- 

    `      Name  test1 test2  test3`
            ad1    43    44      42
            ad2    32    32      23
            ad3    21    26      23

期望的输出:3 个单独的文件 test1.txt , test2.txt, test3.txt

test1.txt = Name  test1
             ad1   43
             ad2   32
             ad3   21

   test2.txt = Name  test2
                 ad1   44
                 ad2   32
                 ad3   26

   test3.txt = Name  test3
                 ad1   42
                 ad2   23
                 ad3   23

【问题讨论】:

  • 您的意思是要将它们写入新文件?
  • 你需要这个是动态的吗?还是仅针对这种特定情况?
  • @AnandaMahto,是的,我想把它们写成新文件。

标签: r dataframe subset


【解决方案1】:

这个循环应该可以工作

for(i in 1:(length(colnames(b))-1)){
  temp <- as.data.frame(cbind(b$Name,b$test1))
  colnames(temp) <- c("Name",paste("test",i,sep=""))
  write.csv(temp,file=paste("test",i,".txt",sep=""))
}

这样,如果您的文件和列数发生变化,它仍然可以工作

【讨论】:

    【解决方案2】:

    简单的事情就是循环。

    df <-data.frame(Name=c("ad1","ad2","ad3"),test1=c(43,32,21),
    test2=c(44,32,26),test3=c(42,23,23))
    
    for (i in 2:ncol(df)) {
            curdf<-subset(df,,select=(c(1,i)))
            write.table(curdf, paste(names(df)[i],".txt",sep=""), sep="\t")
    }
    

    【讨论】:

    • 它只给出 1 个文件作为输出,test3.txt
    【解决方案3】:

    您可以将其拆分为 list,如下所示:

    lapply(2:ncol(df1), function(x) df1[c(1, x)])
    

    或者您可以使用以下方式将它们写入新文件(例如 csv 文件):

    lapply(2:ncol(df1), function(x) {
      write.csv(df1[c(1, x)], file = sprintf("%s.txt", names(df1[x])))
    })
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-11-08
      • 2015-01-15
      • 2020-01-08
      • 1970-01-01
      • 2019-04-21
      • 1970-01-01
      • 2021-03-12
      • 1970-01-01
      相关资源
      最近更新 更多