0

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
NewBee
  • 990
  • 1
  • 7
  • 26
  • You are trying to write a prop_test. It wont write it the same way you see it. You will have to capture the output and cat it accordingly – Onyambu Oct 12 '21 at 21:54
  • What package are you using for the `prop_test()` function? That's not a base R function. It looks like there is a custom print() function which is trying to do formatting. There is likely an option to disable that somewhere. It's easier to help you if you include a simple [reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) with sample input that can be used to test and verify possible solutions. – MrFlick Oct 12 '21 at 21:57

1 Answers1

1

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)

lovalery
  • 4,524
  • 3
  • 14
  • 28