6

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!

Rashedul Islam
  • 879
  • 1
  • 10
  • 23

3 Answers3

9

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))
nograpes
  • 18,623
  • 1
  • 44
  • 67
  • would you know how to exclude `jitter` on missing or `NA` values? I'm trying to avoid removing rows with any missing or `NA` values (e.g. `df[complete.cases(df), ]`). – user63230 Jun 11 '19 at 20:35
4

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)
thepule
  • 1,721
  • 1
  • 12
  • 22
  • 1
    This is unsafe. Don't use `apply()` on a dataframe unless you want to coerce it to a to matrix where all columns are of the same type. – Uwe Jun 26 '16 at 12:47
2

Just adding random numbers?

df_jit <- df + matrix(rnorm(nrow(df) * ncol(df), sd = 0.1), ncol = ncol(df))
Alex
  • 4,925
  • 2
  • 32
  • 48