- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to round each value in columns if some columns are categorical in R data frame?
To round each value in columns if some columns are categorical in R data frame, we can follow the below steps −
First of all, create a data frame.
Then, use numcolwise function from plyr package to round each value in columns if some columns are categorical.
Example
Create the data frame
Let’s create a data frame as shown below −
Level<-sample(c("low","medium","high"),25,replace=TRUE) Group<-sample(c("first","second"),25,replace=TRUE) DV1<-rnorm(25) DV2<-rnorm(25) df<-data.frame(Level,Group,DV1,DV2) df
Output
On executing, the above script generates the below output(this output will vary on your system due to randomization) −
Level Group DV1 DV2 1 low first 0.3113086 -0.560410192 2 high second 1.2462502 -0.839353354 3 high second -0.1069003 0.876603377 4 low second 0.7132453 0.444083125 5 high second -0.9718300 0.719396980 6 medium first -1.1686395 0.692503766 7 high first 0.2996904 1.549099366 8 medium first 0.1843041 -0.623725508 9 medium first -0.2806531 0.265089090 10 medium second -0.1707617 0.783538873 11 medium second -0.3580571 0.367009599 12 low second -0.7904927 -0.363554432 13 high second 1.2020259 -0.990149369 14 medium first 0.1223149 -0.096059087 15 high second -0.2941084 -0.584607516 16 medium first 0.8305360 -0.521546585 17 high first 1.3346562 -0.234318326 18 medium first -0.6467870 -0.002709633 19 medium second 0.2400778 -0.969352846 20 low first 0.4702012 0.168694928 21 medium first -0.5836102 0.145309996 22 low second 1.0728229 0.641423060 23 low first -0.2079424 -0.603290667 24 medium first 0.6148493 -0.919263451 25 high second -0.1642258 0.065443836
Round each value in columns if some columns are categorica
Using numcolwise function from plyr package to round each value in numerical columns if some columns are categorical in the data frame df −
Level<-sample(c("low","medium","high"),25,replace=TRUE) Group<-sample(c("first","second"),25,replace=TRUE) DV1<-rnorm(25) DV2<-rnorm(25) df<-data.frame(Level,Group,DV1,DV2) library(plyr) numcolwise(round)(df)
Output
DV1 DV2 1 0 -1 2 1 -1 3 0 1 4 1 0 5 -1 1 6 -1 1 7 0 2 8 0 -1 9 0 0 10 0 1 11 0 0 12 -1 0 13 1 -1 14 0 0 15 0 -1 16 1 -1 17 1 0 18 -1 0 19 0 -1 20 0 0 21 -1 0 22 1 1 23 0 -1 24 1 -1 25 0 0
Advertisements