Reputation: 4636
Rather than pivoting is it possible to round values of a dataset by rows instead of columns? The standard way is to round columns using mutate_at
or now with across
but I would prefer to do by specific rows:
library(tidyverse)
set.seed(10)
df <- data.frame(let = sample(letters, 20),
x = rnorm(20),
y = rnorm(20) + 10,
z = rnorm(20) + 30)
df
#for rows where "let" = i, j, k, h round to 2 decimal places using ~round(., 2)
round_2 = c("i", "j", "k", "h")
#for rows where "let" = a, b, c, d, e round to decimal places using ~round(., 0)
round_0 = c("a", "b", "c", "d")
#typical type approach with columns
#df %>%
# mutate(across(matches("x|y"), ~round(., 0)))
#df %>%
# mutate(across(matches("z"), ~round(., 2)))
Maybe rowwise
could be used here?
thanks
Upvotes: 1
Views: 491
Reputation: 639
Since let
column is available inside the mutate function you could do:
df %>%
mutate_at(c('x', 'y', 'z'), ~round(., case_when(
let %in% round_0 ~ 0,
let %in% round_2 ~ 2
)))
For dplyr >= 1.0.0
:
df %>%
mutate(across(matches('x|y|z'), ~round(., case_when(
let %in% round_0 ~ 0,
let %in% round_2 ~ 2
))))
Result:
let x y z
1 k -0.71 9.87 29.94
2 i -0.37 9.22 29.81
3 j -1.32 10.09 31.01
4 p NA NA NA
5 l NA NA NA
6 h 1.69 11.77 30.82
7 g NA NA NA
8 s NA NA NA
9 o NA NA NA
10 r NA NA NA
11 x NA NA NA
12 t NA NA NA
13 w NA NA NA
14 b 0.00 10.00 29.00
15 u NA NA NA
16 v NA NA NA
17 q NA NA NA
18 f NA NA NA
19 n NA NA NA
20 c 1.00 11.00 31.00
Upvotes: 1
Reputation: 27732
data.table
solution
library( data.table )
setDT(df)
cols = c("x", "y", "z")
df[ let %in% round_2, (cols) := round( .SD, digits = 2), .SDcols = cols][]
df[ let %in% round_0, (cols) := round( .SD, digits = 0), .SDcols = cols][]
# let x y z
# 1: k -0.710000000 9.870000 29.94000
# 2: i -0.370000000 9.220000 29.81000
# 3: j -1.320000000 10.090000 31.01000
# 4: p 1.280597456 10.064564 30.07160
# 5: l 0.667415054 10.115208 31.36119
# 6: h 1.690000000 11.770000 30.82000
# 7: g 0.001261409 9.186451 30.52619
# 8: s -0.742461312 9.910625 29.57074
# 9: o 0.609684421 10.314817 30.16474
# 10: r -0.989606379 7.939459 29.22681
# 11: x -0.034848335 9.400197 29.62148
# 12: t 0.847159906 9.046434 31.65189
# 13: w 1.525498006 10.557506 28.32389
# 14: b 0.000000000 10.000000 29.00000
# 15: u 0.210143002 10.973221 29.42507
# 16: v -0.081721617 10.101948 31.08997
# 17: q 0.013249400 8.119381 30.12649
# 18: f -1.203106335 8.456234 29.27683
# 19: n -0.261154359 9.766260 31.42620
# 20: c 1.000000000 11.000000 31.00000
Upvotes: 1