Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add jitter in a data frame in R

Tags:

r

jitter

Input:

df = data.frame(col1 = 1:5, col2 = 5:9)
rownames(df) <- letters[1:5]


#add jitter
jitter(df) #Error in jitter(df) : 'x' must be numeric

Expected output: jitter will be added to the columns of df. Thanks!

like image 451
Rashedul Islam Avatar asked Jun 26 '16 11:06

Rashedul Islam


People also ask

How does jitter work in R?

The jitter() function is used to add noise to the numeric vector. The jitter() function takes a numeric vector and amount of noise to be added and returns a numeric vector of the same length but with an amount of noise added in order to break ties.


3 Answers

jitter is a function that takes numeric as input. You cannot simply run jitter on the whole data.frame. You need to loop through the columns. You can do:

data.frame(lapply(df, jitter))
like image 56
nograpes Avatar answered Oct 04 '22 03:10

nograpes


Jitter is to be applied to a numerical vector, not a dataframe. If you want to apply Jitter to all your columns, this should do:

apply(df, 2, jitter)
like image 41
thepule Avatar answered Oct 04 '22 03:10

thepule


Just adding random numbers?

df_jit <- df + matrix(rnorm(nrow(df) * ncol(df), sd = 0.1), ncol = ncol(df))
like image 27
Alex Avatar answered Oct 04 '22 05:10

Alex