[R] Data Frame Construction

    This post covers data frame construction in R Studio.


    1. Data imputation

    This method involves data imputation and employing data.frame() function.

    The table below displays fertility rate and unemployment rate of South Korea, Japan, Canada, and United States in 2020.

    Country Fertility rate Unemployment rate
    Korea 0.84 3.94
    Japan 1.33 2.77
    Canada 1.50 9.56
    USA 1.64 8.09

    (I used data of OECD DATA from the following links.

    https://data.oecd.org/pop/fertility-rates.htm#indicator-chart

    https://data.oecd.org/unemp/unemployment-rate.htm )


    1) 2 step method

    You can generate the variables first and then use data.frame() function.

    #step 1 - variable generation
    country <- c("Korea", "Japan", "Canada", "USA")
    FTR <- c(0.84, 1.33, 1.50, 1.64)
    UPR <- c(3.94, 2.77, 9.56, 8.09)
    #step 2 - generation and designation of data frame 
    df1 <- data.frame(country, FTR, UPR)
    df1
    

    You will get results as below.

    > df1
      country  FTR  UPR
    1   Korea 0.84 3.94
    2   Japan 1.33 2.77
    3  Canada 1.50 9.56
    4     USA 1.64 8.09
    

    2) 1 step method

    It is also possible to generate variables within the data.frame() function.

    Note that the variables must be separated by ',(comma)'s. 

    df1 <- data.frame(country = c("Korea", "Japan", "Canada", "USA"),
                      FTR = c(0.84, 1.33, 1.50, 1.64),
                      UPR = c(3.94, 2.77, 9.56, 8.09))
    

    *However, researchers often simply import data sets from external sources (such as Excel) rather than typing in values (data imputation) in R Studio.

    To refer to how to import data sets, please follow the link below.

    https://ik-lab.blogspot.com/2022/06/r-studio-data-import.html



    2. Loading data

    Other than constructing data frame oneself, we can simply load data.

    Here, we are going to load 'mpg' from 'ggplot2' package and view it.

    install.packages("ggplot2")
    library(ggplot2)
    mpg <- as.data.frame(ggplot2::mpg)
    View(mpg)
    

    Post a Comment

    0 Comments