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