how to add rows to exist data frame based on condition


I have below df and need to create another df2 like below based on df1.
the same rows need to add to same df1 with change of column2 values.

#> column1 column2
#> 1 a
#> 2 b
#> 3 c

#> column1 column2
#> 1 a
#> 2 b
#> 3 c
#> 1 x
#> 2 x
#> 3 x

Thank you,

Does this do what you want?

df1 <- data.frame(column1 = 1:3, column2 = c("a","b","c"))
NewRows <- df1
NewRows$column2 <- "x"
df2 <- rbind(df1, NewRows)
#>   column1 column2
#> 1       1       a
#> 2       2       b
#> 3       3       c
#> 4       1       x
#> 5       2       x
#> 6       3       x

Created on 2023-10-31 with reprex v2.0.2

Hi ,
THank you !

I have tried above code and it worked , but not as my expected output , here is actual data

Above data frame have 52 onservations and 8 variables and need to cahnge TRT01P and TRT01PN values and bind the dataset to actual data so total 104 observations and 8 varibales

IN 104 observation 52 observations TRT01p and TRT01PN has same values and other 52 observations TRT01p=X and TRT01pn=99

please helo me how to do that data frame.

Thank you,

change them to what ?

Hi raja,

Here's another alternative, based on tidyerse:

  # use tidyverse libraries

  # create sample data frame
  original <- data.frame( usubjid = 1:54,
                          trt01p  = sample( letters, 54, replace = TRUE) ,
                          trt01pn = sample( 1:10, 54, replace = TRUE) )
  # create temporay dataframe with new values
  new <- 
    original %>%                # use the orignal data frame
    mutate( trt01p = "x",       # change column values
            trt01pn = 99 )      # change column values
  # combine the two data frames into a new one
  combined <- 
    bind_rows( original, new )
  # remove old dataframes from memory, if no longer needed.
  rm ( original, new )

It is a bit long for the small thing that you want to do, but I like this style because it is relatively clear what you are doing in what step.

Which means you hopefully can adjust the code easily to the more complicated things you want to do later

Also: When using tidyverse, the dypler cheat-sheets are a good help to figure out how to solve certain things. :slight_smile:

dplyr cheat sheet

PS: If an answer solves your problem, please click on the "solution" button below.

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.