Rounding selected columns of data.table in R
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
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
dplyr
works on data.table
objects! dplyr::mutate
(as of dplyr 1.0.0 major update) incorporates flexible specification of columns and functions for modifying the data, using across
.
To specify all columns that have numeric data:
mydf %>% mutate(across(where(is.numeric), round, 1))
- which is the same as
mydf %>% mutate(across(where(is.numeric), ~round(., 1)))
- which is the same as
To specify all columns with names that start with "vnum":
mydf %>% mutate(across(starts_with("vnum"), round, 1))
It is slightly more wordy than the previous mutate_if
(which still works but is retired) but it is consistent with other possible specifications and allows for more variations.
Old answer
You can use mutate_if
with the added benefit of rounding a column only if it is numeric
mydf %>% mutate_if(is.numeric, round, 1)