1

I have created a function to reshape (pivot) data, but the last part of the function is to cbind several columns into the df.

pivot_df <-  function(df, new_col, col1, col2, col3) {
     df_col_selected <- df[ , c(col1, col2, col3)]
     df_col_selected_reshaped <- reshape(
       df_col_selected, 
       idvar = col2, 
       timevar = col3,
       direction = "wide"
    )
     df_reshaped <-cbind(df_col_selected_reshaped, new_col, col1)
}

So if I call the function and give the names of the columns, it gives me desired outcome.

pivot_df(df, new_col, col1, col2, col3)

But I want to have a flag or ifelse inside this function for new_col. I mean new_col will be skipped in the last cbind if it is not written in the function, like this:

pivot_df(df, col1, col2, col3)

This still performs the df_reshaped <-cbind (df_col_selected_reshaped, new_col, col1) but there will be no new_col at the end.

I know I can create a separate function without new_col there, but I want to have a single function that can do both. Thanks

Sotos
  • 51,121
  • 6
  • 32
  • 66
Zmnako Awrahman
  • 538
  • 7
  • 19

1 Answers1

1

You can set new_col to NULL as default:

pivot_df <-  function(df, new_col = NULL, col1, col2, col3) {
    df_col_selected <- df[ , c(col1, col2, col3)]
    df_col_selected_reshaped <- reshape(
        df_col_selected, 
        idvar = col2, 
        timevar = col3,
        direction = "wide"
    )
    if(!is.null(new_col)){
        df_reshaped <-cbind(df_col_selected_reshaped, new_col, col1)
    }else{
        df_reshaped <-cbind(df_col_selected_reshaped, col1)
    }
}
tobiasegli_te
  • 1,413
  • 1
  • 12
  • 18