I'm trying to split columns in a dataframe and place them next to each other based on a single factor column. I would like to take this:
TOD Value
1 Day 135
2 Day 513
3 Day 567
4 Day 848
5 Day 578
6 Night 145
7 Night 267
8 Night 589
9 Night 258
10 Night 278
11 Night 149
and turn it into this:
TOD Value TOD_2 Value_2
1 Day 135 Night 145
2 Day 513 Night 267
3 Day 567 Night 589
4 Day 848 Night 258
5 Day 578 Night 278
The last row (11) needs to be removed so that all columns are of equal length. I can't have 0's or NA's as a 'filler' row. How do I do this? I have code that can accomplish the splitting part, but only if the columns are all equal:
df2<- df %>%
group_split(TOD) %>%
Map(function(x, y) {names(x) <- paste(names(x), y, sep = "_"); x}, ., 1:length(.)) %>%
bind_cols()
this also works:
df2<- do.call(cbind, split(df, df$TOD)) |>
setNames(c(names(df), paste0(names(df), "_2")))
I need to add something that will remove extra rows if the 'Value_2' column exceeds the number of values in the original 'Value' column.