11.3 Exercise 6.

Create the script “exercise6.R” and save it to the “Rcourse/Module2” directory: you will save all the commands of exercise 6 in that script.
Remember you can comment the code using #.

correction

11.3.1 Exercise 6a. Input / output

1- Download folder “i_o_files” in your current directory with:

All files that will be used for exercise 6 are found in the i_o_files folder !

2- Read in the content of ex6a_input.txt using the scan command; save in object z

How many elements are in z?

correction

3- Sort z: save sorted vector in object “zsorted”. ?sort

correction

4- Write zsorted content into file ex6a_output.txt. ?write

correction

5- Check the file you produced in the RStudio file browser (click on the file in bottom-right panel, “Files” tab). Save the content of zsorted again but this time setting the argument “ncolumns” to 1: how does the file look now?

correction

11.3.2 Exercise 6b - I/O on data frames: play with the arguments of read.table

1- field separator

  • Read ex6b_IO_commas_noheader.txt in object fs. ?read.table. What are the dimensions of fs?

correction

  • Fields/columns are separated by commas: change the default value of the “sep” argument and read in the file again. What are now the dimensions of fs?

correction

2- field separator + header

  • Read ex6b_IO_commas_header.txt in object fs_c. What are the dimensions of fs_c ?

correction

  • Check head(fs_c) and change the default field separator to the appropriate one.

correction

  • The first row should to be the header (column names)! Change the default value of the header parameter and read in the file again. What are now the dimensions of fs_c ?

correction

3- skipping lines

  • Read ex6b_IO_skip.txt in object sk.

correction

Is R complaining ?

Check “manually” the file (open it in the R Studio file browser).

  • The “skip” argument allows you to ignore one or more line(s) before reading in a file. Introduce this argument with the appropriate number of lines to skip, and read in the file again.

correction

  • Is R still complaining? What are now the dimensions of sk ?

  • Change the default field separator. What are now the dimensions of sk ?

correction

4- Comment lines

  • Read ex6b_IO_comment.txt in object cl.

correction

Is R complaining again ? Check manually the file and try to find out what is wrong…

What is the “comment.char” argument used for ? Adjust the comment.char argument and read in the file again.

correction

  • Adjust also the header and sep arguments to read in the file correctly. What are now the dimensions of cl?

correction

4- final

  • Read ex6b_IO_final.txt in object “fin”.

correction

  • Adjust the appropriate arguments of “write.table” according to what you have learnt so far, in order to obtain the data frame “fin” of dimensions 167 x 4.

correction