3.2 Importing Excel Files

One way to get Excel files directly into R is by using the XLConnect package. For this example, you will need the “happy.xlsx” file. Check if the file is in your project directory. If not, you can download it here.

Install the package, and try using the readWorksheetFromFile() function to load the data, and assign it to an object called df:

# Run this only once, to download and install the package:
install.packages("XLConnect")
# Load the package:
library(XLConnect)
# Read the 'Happy to help' Excel file into 'df':
df <- readWorksheetFromFile("happy.xlsx",
                            sheet = 1)

3.2.1 Inspect the data

R does not work with a single spreadsheet (SPSS or Excel). Instead, it can keep many objects in memory. The object df is a data.frame; an object that behaves similar to a spreadsheet. To see a description of the object, look at the Environment tab in the top right of Rstudio, and click the arrow next to df.

As you can see, the on the top-right pane Environment, your file is now listed as a data set in your RStudio environment.

You can make a quick copy of this data set by assigning the df object to a new object. This way, you can edit one, and leave the other unchanged. Assign the object df to a new object called happy:

happy <- df

You can also have a look at the contents of df by clicking the object in the Environment panel, or running the command head(df):

Here’s a (shortened) table for the data

study_id d vi n1i n2c sex age location donorcode interventioncode controlcode recipients outcomecode
Aknin, Barrington-Leigh, et al. (2013) Study 3 0.46 0.0205290 100 100 38 21.0 Canada / South Africa Typical Prosocial Spending Self Help Anonymous Sick Children PN Affect
Aknin, Barrington-Leigh, et al. (2013) Study 3 0.13 0.0200422 100 100 38 21.0 Canada / South Africa Typical Prosocial Spending Self Help Anonymous Sick Children Life Satisfaction
Aknin, Broesch, et al. (2015) Study 1 0.93 0.1704788 13 13 42 45.0 Vanuatu Typical Prosocial Spending Self Help Family / Friends PN Affect
Aknin, Broesch, et al. (2015) Study 2 0.30 0.1011250 20 20 70 3.0 Vanuatu Typical Other Neutral Activity Puppet Other
Aknin, Dunn, et al. (2013) Study 3 0.24 0.0805760 25 25 34 21.0 Canada Typical Prosocial Spending Self Help Someone Other
Aknin, Fleerackers, et al. (2014) 0.38 0.0342225 60 59 41 19.9 USA Typical Prosocial Spending Self Help Anonymous Sick Children PN Affect