简体   繁体   中英

After imputation, how to round to nearest level of a factor

I have imputed missing values in the following data frame in column q1. q1 q1. q1 is a factor with the levels 0,20,40,60,80,100 . I need to round the column q1 to nearest level of factors, number 49 and 91 need to be rounded. Does anyone have a solution for this problem?, thanks in advance!

id <- rep(c(300,450), each=6)
> visit <- rep(1:6,2)
> trt <- rep(c(0,"A",0,"B",0,"C"),2)
> q1 <- c(0,100,0,89,0, 60,0,85,0,40,0, 20)
> df <- data.frame(id,visit,trt,q1)
> df
    id visit trt  q1
1  300     1   0   0
2  300     2   A 100
3  300     3   0   0
4  300     4   B  49
5  300     5   0   0
6  300     6   C  60
7  450     1   0   0
8  450     2   A  91
9  450     3   0   0
10 450     4   B  40
11 450     5   0   0
12 450     6   C  20
>

Maybe you could use plyr 's round_any function here which would round to nearest multiple of 20 in this case.

plyr::round_any(df$q1, 20)
#[1]   0 100   0  80   0  60   0  80   0  40   0  20

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM