Mixalis
Mixalis

Reputation: 542

Dynamically append column to dataframe R

How can I append a column in a dataframe?

I'm iterating over my datamatrix and if some data agree with a threshold I've set, I want to store them in a 1-row dataframe so I can print at the end of the loop.

My code, looks like this:

for (i in 1:nrow(my.data.frame)) {
    # Store gene name in a variable and use it as row name for the 1-row dataframe.

    gene.symbol <- rownames(my.data.frame)[i]

    # init the dataframe to output
    gene.matrix.of.truth <- data.frame(matrix(ncol = 0, nrow = 0))

    for (j in 1:ncol(my.data.frame)) {
        if (my.data.frame[i,j] < threshold) {
            str <- paste(colnames(my.data.frame)[j], ';', my.data.frame[i,j], sep='')

            # And I want to append this str to the gene.matrix.of.truth
            # I tried gene.matrix.of.truth <- cbind(gene.matrix.of.truth, str) But didn't get me anywhere.

        }
    }

    # Ideally I want to print the dataframe here.
    # but, no need to print if nothing met my requirements.
    if (ncol(gene.matrix.of.truth) != 0) {
        write.table(paste('out_',gene.symbol,sep=''), gene.matrix.of.truth, row.names = T, col.names = F, sep='|', quote = F)
    }        
}

Upvotes: 1

Views: 2739

Answers (1)

lebelinoz
lebelinoz

Reputation: 5068

I do this sort of thing all the time, but with rows instead of columns. Start with

gene.matrix.of.truth = data.frame(x = character(0))

instead of the gene.matrix.of.truth <- data.frame(matrix(ncol = 0, nrow = 0)) you have at initiation. Your append step inside the for j loop will be

gene.matrix.of.truth = rbind(gene.matrix.of.truth, data.frame(x = str))

(i.e. create a dataframe around str and append it to gene.matrix.of.truth).

Obviously, your final if statement will be if(nrow(...)) instead of if(ncol(...)), and if you want the final table as a big row you'll need t to transpose your dataframe at printing time.

Upvotes: 1

Related Questions