I'm turning some long-form data into wide-form. When I transform my rows to columns, they appear in the order 1, 10, 100 rather than 1,2,3, etc. How do I fix this? I have 100s of rows so I'd rather not manually type out the order.
I know this is an issue with the column names being strings and I attempted to simply use select(), however, this removes my cluster column. I also have tried the standard way of renaming my columns (data <- data[c("A", "B", "C")])
.
I've also taken a look at the following threads and can't seem to parse it out. Reordering columns in a large dataframe Preserve order of columns when going from wide to long format R: Reorder columns from dcast output numerically instead of lexicographically
Here is my code:
library(reshape2)
library(data.table)
library(tidyverse)
library(tidyr)
library(gtools)
library(stringr)
rf_83_88 <- read.csv('Google Drive File Stream/My Drive/Bang_RIA/bang_83_05_rainfall_avg/Bangladesh-precipitation-decadal-83-88.csv')
groupdata_1 <- dcast(setDT(rf_83_88), cluster ~
paste0("precipitation", rowid(cluster)), value.var = "precipitation")
Here is the df sample it produces:
cluster precipitation1 precipitation10 precipitation100
Akhai Bari _ 1 0 11.730278 11.12267
Akhai Bari _ 2 0 10.130148 12.53500
When I try:
test_select <- select(groupdata_1, num_range("precipitation", 0:nrow(groupdata_1))
, the df becomes ordered, however it drops cluster.
I'm relatively new to R (and stack) and tried reading the documentation to no avail. Any help would be appreciated. Thanks!