Script works when run on console, but gives errors when executed with "Run all"

I'm using RStudio 2023.06.1, R 4.3.0, on a Windows 10.
I am reading a ".sav" (SPSS) file, directly converting it into data.frame, and extracting and reformating some columns. Nothing advanced.
I use foreign::read.spss with
The possible problem is that the file has German characters, also in the column names. It is all correctly recognized, at least when run manually on the console. Everything works fine.
When I run Ctrl+Shift+S I get errors which seem to fall exactly in such columns with German character "ä ö ü".
The error I get is "arguments imply differing number of rows", so it is not saying the column doesn't exist, but it is apparently returning an empty vector.
I also tried opening the .sav file with haven::read_sav, but there I cannot even open the file. Once again, it works 100% fine run on the console, but with "Run all" I get "Error in : cannot xtfrm data frames", which I don't even know what is about.

Edit: when I ask colnames() the column name comes correctly as "WSTÜGOK2"
I am trying to get the values with $WSTÜGOK2.
When I try [,"WSTÜGOK2"] and run, I get the error
... "WSTÃœGOK2") : undefined columns selected

So depending on how I run the code the encoding used is different? How to work like this? and how to work around this, if the colnames() returns the column name correctly but the Run understands my script in wrong encoding?

Does anyone have a light on this? I'm very clueless right now.
Thank you very much!

Alright, I made it work by changing the encoding when reading the script and when reading the .sav database. But that doesn't explain why it was running correctly in the console always but not with the Run All, considering that print colnames was printing it correctly even without the "correct" encoding.

Try File | Reopen with encoding and choose the UTF-8 option (should be top)

colnames(mtcars)[1] <- "WSTÜGOK2"
#>  [1] 21.0 21.0 22.8 21.4 18.7 18.1 14.3 24.4 22.8 19.2 17.8 16.4 17.3 15.2 10.4
#> [16] 10.4 14.7 32.4 30.4 33.9 21.5 15.5 15.2 13.3 19.2 27.3 26.0 30.4 15.8 19.7
#> [31] 15.0 21.4

Created on 2023-08-01 with reprex v2.0.2

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.