Search code examples
rsink

sink produces weird characters


I am using sink to paste my output to a text file: using the gss data in this example.

library(gss)
library(infer)

con <- file(paste0(dir_output, "test.txt"),encoding = "UTF-8")
sink(con, split = T)

cols <- gss %>% select(where(is.factor)) %>% select(-sex) %>% names(.)
out <- vector('list', length(cols))
names(out) <- cols
for(i in cols) {
  out[[i]] <- prop_test(gss, reformulate("sex", response = i))
  print(out[i])
}
sink(file = NULL)

The output print fine into in the R console, but it prints weirdly into the text file. Any idea's why this might be happening? This is the output in the text file...

$college
[38;5;246m# A tibble: 1 x 6[39m
  statistic chisq_df p_value alternative lower_ci upper_ci
      [3m[38;5;246m<dbl>[39m[23m    [3m[38;5;246m<dbl>[39m[23m   [3m[38;5;246m<dbl>[39m[23m [3m[38;5;246m<chr>[39m[23m          [3m[38;5;246m<dbl>[39m[23m    [3m[38;5;246m<dbl>[39m[23m
[38;5;250m1[39m 0.000[4m0[24m[4m2[24m[4m0[24m4        1   0.996 two.sided    -[31m0[39m[31m.[39m[31m0[39m[31m91[4m7[24m[39m    0.101

$partyid
[38;5;246m# A tibble: 1 x 3[39m
  statistic chisq_df p_value
      [3m[38;5;246m<dbl>[39m[23m    [3m[38;5;246m<dbl>[39m[23m   [3m[38;5;246m<dbl>[39m[23m
[38;5;250m1[39m      12.9        3 0.004[4m8[24m[4m4[24m

Solution

  • I guess the problem is that you are using the package crayon to make the output in the console more readable. To make those weird characters disappear in your text file you need to insert this line of code at the beginning of your script to modify the options:

    options(crayon.enabled = FALSE,"crayon.colors" = 1)

    The disadvantage is that you lose the colors in the console, but I never found a better solution...

    If at any time you want to put the colors back in the console, you must enter the following line of code:

    options(crayon.enabled = TRUE,"crayon.colors" = 8)