Kryo
Kryo

Reputation: 933

how to split a dataframe in to separate dataframe based on the number of columns

I have a dataframe and Im trying to split the dataframe into separate datasets with the file name of dataset as colnames of dataframe

df1 <- 

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

desired output: 3 separate files 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

Upvotes: 0

Views: 106

Answers (3)

Buzz Lightyear
Buzz Lightyear

Reputation: 844

This loop should work

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=""))
}

This way if your number of files and columns changes, it will still work

Upvotes: 1

Timo Kvamme
Timo Kvamme

Reputation: 2964

something simple would be a loop.

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")
}

Upvotes: 1

A5C1D2H2I1M1N2O1R2T1
A5C1D2H2I1M1N2O1R2T1

Reputation: 193517

You can split it into a list with something like this:

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

Or you can write them out to new files (say csv files) with something like this:

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

Upvotes: 2

Related Questions