Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rounding selected columns of data.table in R

Tags:

r

data.table

I have following data and code to round selected columns of this data.table:

> dput(mydf)
structure(list(vnum1 = c(0.590165705411504, -1.39939534199836, 
0.720226053660755, -0.253198380120377, -0.783366825121657), vnum2 = c(0.706508400384337, 
0.526770398486406, 0.863136084517464, 0.838245498016477, 0.556775856064633
), vch1 = structure(c(2L, 4L, 1L, 3L, 3L), .Label = c("A", "B", 
"C", "E"), class = "factor")), .Names = c("vnum1", "vnum2", "vch1"
), row.names = c(NA, -5L), class = c("data.table", "data.frame"
))

> mydf[,round(.SD,1),]
Error in Math.data.frame(list(vnum1 = c(0.590165705411504, -1.39939534199836,  : 
  non-numeric variable in data frame: vch1

> cbind(mydf[,3,with=F], mydf[,1:2,with=F][,round(.SD,1),])
   vch1 vnum1 vnum2
1:    B   0.6   0.7
2:    E  -1.4   0.5
3:    A   0.7   0.9
4:    C  -0.3   0.8
5:    C  -0.8   0.6

Is there a better method (shorter code)? Thanks for your help.

like image 982
rnso Avatar asked Dec 23 '14 02:12

rnso


People also ask

How do you round off columns in R?

Round function in R, rounds off the values in its first argument to the specified number of decimal places. Round() function in R rounds off the list of values in vector and also rounds off the column of a dataframe.

How do you round a table in R?

To round values in proportion table in R, we can first save the proportion table in an object and then use the round function.


2 Answers

Using dplyr

If you want to round multiple columns at once:

mydf %>% mutate_at(vars(vnum1, vnum2), funs(round(., 1))) 

Or, if you want to change all columns except "vch1":

mydf %>% mutate_at(vars(-vch1), funs(round(., 1))) 

Or, if you want to change all columns starting with "vnum":

mydf %>% mutate_at(vars(starts_with("vnum")), funs(round(., 1))) 

Or, if you want to change only numeric columns:

mydf %>% mutate_if(is.numeric, ~round(., 1)) 

You get:

  vnum1 vnum2 vch1 1   0.6   0.7    B 2  -1.4   0.5    E 3   0.7   0.9    A 4  -0.3   0.8    C 5  -0.8   0.6    C 
like image 66
Steven Beaupré Avatar answered Sep 19 '22 13:09

Steven Beaupré


If you don't mind overwriting your original mydf:

cols <- names(mydf)[1:2]
mydf[,(cols) := round(.SD,1), .SDcols=cols]
mydf

#   vnum1 vnum2 vch1
#1:   0.6   0.7    B
#2:  -1.4   0.5    E
#3:   0.7   0.9    A
#4:  -0.3   0.8    C
#5:  -0.8   0.6    C
like image 44
thelatemail Avatar answered Sep 19 '22 13:09

thelatemail