Search code examples
rrowadditiondata-wrangling

Add new rows to dataframe populating one column with a string and another with values from 2nd dataframe column in R


I have the following string and 2 dataframes. There are many sets of this configuration (components, fueltypes, etc). I will create one set as an example. If components, fueltypes, etc has no data then I want to fill them as shown below.

Doing this operation is contingent on components, etc not having any data rows.

rocketnum <- "0000"
events_components <- data.frame(unique_event=c("thrust","azimuth","gyro","spin"))

#create empty df with column names but no data
components <- data.frame(rocketnum=character(),
                 event=character(),
                 powerlevel=character(),
                 propellant=character(),
                 stringsAsFactors=FALSE)

events_components:

enter image description here

components:

enter image description here

and want the following as a result in components:

enter image description here


Solution

  • If I do not misunderstand the question, then you want to populate the components table using rocketnum and events_components, if components is empty. This could be done by using

    if (nrow(components) == 0) {
        
        # extend the empty data frame by the needed number of rows
        components[1:nrow(events_components), ] <- NA
        
        components$rocketnum <- rocketnum
        
        components$event <- events_components$unique_event
    }
    
    components
    
      rocketnum   event powerlevel propellant
    1      0000  thrust       <NA>       <NA>
    2      0000 azimuth       <NA>       <NA>
    3      0000    gyro       <NA>       <NA>
    4      0000    spin       <NA>       <NA>