w3resource

Create an Empty Data Frame with Various Column Types in R


Write a R program to create an empty data frame.

Sample Solution :

R Programming Code :

 # Create an empty data frame with various column types
df = data.frame(
  Ints = integer(),        # Integer column
  Doubles = double(),      # Double (numeric) column
  Characters = character(), # Character (string) column
  Logicals = logical(),    # Logical (boolean) column
  Factors = factor(),      # Factor column
  stringsAsFactors = FALSE # Do not convert strings to factors by default
)

# Print a message indicating what is being displayed
print("Structure of the empty dataframe:")

# Display the structure of the data frame
print(str(df))

Output:

[1] "Structure of the empty dataframe:"
'data.frame':	0 obs. of  5 variables:
 $ Ints      : int 
 $ Doubles   : num 
 $ Characters: chr 
 $ Logicals  : logi 
 $ Factors   : Factor w/ 0 levels: 
NULL                         

Explanation:

  • df = data.frame(...): Creates an empty data frame df with the following column types:
    • Ints = integer(): An integer column.
    • Doubles = double(): A numeric (double) column.
    • Characters = character(): A character (string) column.
    • Logicals = logical(): A logical (boolean) column.
    • Factors = factor(): A factor column (used for categorical data).
    • stringsAsFactors = FALSE: Prevents automatic conversion of string columns to factor type.
  • print("Structure of the empty dataframe:"): Prints a message indicating that the structure of the data frame will be shown next.
  • print(str(df)): Prints the structure of the empty data frame df, showing the data types of each column and confirming that it contains no data.

R Programming Code Editor:



Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous: R Programming Data frame Exercises Home.
Next: Write a R program to create a data frame from four given vectors.

Test your Programming skills with w3resource's quiz.

What is the difficulty level of this exercise?



Follow us on Facebook and Twitter for latest update.