mschmidt
mschmidt

Reputation: 117

How to detele row and fill-in column in multiple data.frames at once?

I have over 10 data.frames with the same columns. First column is filled with "!" and I want to change it into data.frame name. Each data frame have over 7 000 rows. Last row in each data.frame is empty that I want to remove. My goal is to merge the data.frames but preserve the origin of the data in first column.

I have a list of data frame names in temp2, those are also names I want to put into first column of given data frame.

    > str(temp2)
     chr [1:13] "bone_marrow" "colon" "duodenum" "esophagus" "liver" "lymph_node" "rectum" ...

The first column to be filled in by data.frame name in named "Tissue" df$Tissue

I tried to delete last row in each data frame with:

    for (i in 1:length(temp2)) assign(temp2[i], temp2[i][-nrow(temp2[i],)])

and to fill the first column with data frame name with:

    for (i in 1:length(temp2)) paste0(temp2[i], "$Tissue = ", temp2[i])

or

    for (i in 1:length(temp2)) paste0(temp2[i], "$Tissue") <- temp2[i]

the first code (for deleting last rows) returns:

Error in nrow(temp2[i], ) : unused argument (alist())

the second code is silent but does nothing, the last one returns:

Error in paste0(temp2[i], "$Tissue") <- temp2[i] : 
could not find function "paste0<-"

and the final goal to merge all the data frames into one with rbind or merge

    for (i in 1:length(temp2)) allDF = rbind(temp2[i])

Upvotes: 0

Views: 100

Answers (1)

user2474226
user2474226

Reputation: 1502

Let's say your data frames are df1, df2, df3.

First, you can combine them into a list:

dflist <- list(df1, df2, df3)

Then you can create new columns for each of them and strip the last row of each data frame (the head() function with argument -1 removes the last row):

dflist2 <- lapply(1:NROW(dflist), 
    function(i) {dflist[[i]]$Tissue <- temp2[i]; 
                 head(dflist[[i]], -1)}
    )

And, finally, you can bind them into one big dataframe:

mydf <- do.call(rbind, dflist2)

Upvotes: 0

Related Questions