Learning R | How to Create A Data Frame from Scratch

Rawan Tarek
2 min readJan 11, 2021

--

In this article I am going to show you how to :

1.Create a new data frame .
2.factorize and order the ordinal variable.
3.Show the structure of variables and the levels of the ordinal variable.
4.Create another numeric vector and use cbind() to add this vector to the data frame.

First open up R Studio and create a new script file and enter the following code:
Patient_ID<-c(15,16,17,18,19,20,21,22,23,24)
Extent_of_satisfaction <-c(“Indifferent”,”dissatisfied”,”Satisfied”,”Very satisfied “,”Satisfied”,”Indifferent”,”Dissatisfied “,”Satisfied”,”Very dissatisfied”,”Satisfied”)
df<-data.frame(Patient_ID,Extent_of_satisfaction)
So, what’s going on?
First, Using data.frame() function a new data frame was created from scratch with some specifications (one integer variable and one ordinal variable and 10 observations) .
The variables definition : Patient_ID String variable identify the ID of patients in Doctor clinic, Extent_of_satisfaction ordinal character variable showing the satisfaction level of patient toward the clinic and the doctor.

factor_satisfaction<-factor(df $ Extent_of_satisfaction)
Extent_of_satisfaction <- factor(Extent_of_satisfaction,ordered = TRUE,levels =c(“Very satisfied”,”Satisfied”,”Indifferent”,”Dissatisfied”,”Very dissatisfied”))
Extent_of_satisfaction
factor() function is used to categorize the data and store it as levels.

str(df)
str()function is to check that the format and levels of factors are correct.

the_shift<-c(“night”,”day”,”night”,”night”,”day”,”night”,”day”,”night”,”night”,”day”)
new_df<-df
new_df <- cbind(df, the_shift = the_shift)
new_df
attributes(new_df)
new variable the_shift is created using cbind() function then this vector added to the data frame.

dim(new_df)
Dimensions of the data set is checked using dim().

--

--

Rawan Tarek
Rawan Tarek

No responses yet