If you simply need an introduction into R, and less into the Data Science part, I can absolutely recommend this book by Richard Cotton. dt1 <- xīy the way, if you’re having trouble understanding some of the code and concepts, I can highly recommend “An Introduction to Statistical Learning: with Applications in R”, which is the must-have data science bible. In the last lines of code in this chunk, I bind both data frames together, and I reorder the columns back to their original order. I also make a data frame that consists of the leftover columns. I use the get function to run the function as.X by its name, and I do this for all the columns that were selected. (4) The following chunk of code actually has its basis in something I wrote about earlier. (3) Once we have checked if there are actually any columns to convert (not in the above code), we select the column names that should be converted and the once that shouldn’t be. column_order <- colnames(x)Ĭolumn_selection <- grepl(from,sapply(x,class)) ![]() (2) I store the order of the columns somewhere (so we can return it later in the same order), and next I make a selection of the columns that I need to convert. So, before we start blaming R, we need to know this fact. Thus, converting the factor variable to numeric format will take these corresponding integer values. That means factor level 5 has a corresponding numeric value of 13, and level 7 corresponds to 15. Convert 200 into radian measure: 200 180. Test <- convert_columns(test,'integer','numeric') Value 5 is the 13th level, and 7 is the 15th. Same as converting other units, when converting radians to degrees, we need to know the conversion factor. ![]() Test <- convert_columns(test,'character|logical','factor') I call the function twice, to convert the characters/logicals and a second time for the integers. ![]() Here’s the full code I wrote to do it: library(data.table)Ĭolumns_needed <- colnames(x) # (3)Ĭolumns_not_needed <- colnames(x)ĭt1 <- xĭt2 <- xĭt <- convert_columns(dt,'character|logical','factor')ĭt <- convert_columns(dt,'integer','numeric') It contains some characters and logicals that you need as factors, and it contains some integers that you want as numeric. Let’s say you have a data frame (data.table) named dt.
0 Comments
Leave a Reply. |