1.5 Saving an R dataframe as a .csv file


The 'write.csv( )' command can be used to save an R data frame as a .csv file. While variables created in R can be used with existing variables in analyses, the new variables are not automatically associated with a dataframe. For example, suppose we read in a .csv file under the dataframe name 'healthstudy', and that 'age' and 'weight.lb' were variables in this data frame. If we created the 'weight.kg' and 'agecat' variables described above, these variables would be available for analyses in R but would not be part of the 'healthstudy' dataframe. The 'cbind( )' can be used to add new variables to a dataframe (bind new columns to the dataframe). For example,

> healthstudy <- cbind(healthstudy,weight.kg,agecat)

adds the 'weight.kg' variable and the 'agecat' variable to the 'healthstudy' dataframe.

When new variables have been created and added to a dataframe/data set in R, it may be helpful to save this updated data set as a .csv file (which can then be converted to an Excel file or other format). To save a dataframe as a .csv file:

1. First, click on the 'File' menu, click on 'Change directory', and select the folder where you want to save the file.

2. Use the 'write.csv( )' command to save the file:

> write.csv(healthstudy,'healthstudy2.csv')

The first argument (healthstudy) is the name of the dataframe in R, and the second argument in quotes is the name to be given the .csv file saved on your computer. R will overwrite a file if the name is already in use.

1.6 The help( ) and help.search( ) functions


The help() function in R provides details for the different R commands. For example,

> help(read.csv)

gives details relating to the read.csv( ) function, while

> help(mean)

gives details for the mean( ) function.

A question mark can also be used to ask for the help function. For example,

> ?read.csv

> ?mean

gives the same help information as the commands above.

The help( ) function only gives information on R functions. To search more broadly, you can use the 'help.search( ) function. For example,

> help.search("t test")

will search for the string 't test' and indicate R functions that reference this string. There is also a fair amount of R help available over the Internet, and googling, for example, 't test R package' may lead to some helpful sites.