R Program to Split Dataframe

Example 1: Split Dataframe by Row Indexes in R

# Create a data frame
dataframe1 <- data.frame (
  Name = c("Juan", "Alcaraz", "Simantha"),
  Age = c(22, 15, 19),
  Address = c("Nepal", "USA", "Germany")
)

# extract 1st row
print(dataframe1[1, ])

# extract 1st and 3rd row
print(dataframe1[c(1,3), ])

Output

 Name Age Address
1 Juan  22   Nepal
      Name Age Address
1     Juan  22   Nepal
3 Simantha  19 Germany

Here,

  1. dataframe1[1, ] - splits entire elements of 1st row
  2. dataframe1[c(1,3), ] - splits entire elements of 1st and 3rd row

Example 2: Split Dataframe by Column Names in R

# Create a data frame
dataframe1 <- data.frame (
  Name = c("Juan", "Alcaraz", "Simantha"),
  Age = c(22, 15, 19),
  Address = c("Nepal", "USA", "Germany")
)

# extract 1st column
print(dataframe1[, "Name"])

# extract 1st and 3rd column
print(dataframe1[, c("Name", "Address")])

Output

[1] "Juan"     "Alcaraz"  "Simantha"
      Name Address
1     Juan   Nepal
2  Alcaraz     USA
3 Simantha Germany

Here,

  1. dataframe1[,"Name"] - splits entire elements of 1st column
  2. dataframe1[, c("Name","Address")] - splits entire elements of 1st and 3rd column

Note: Instead of column names we can also split data frame using column indexes as: [, 1] and [, C(1,3)]. The output will be the same.

Our premium learning platform, created with over a decade of experience and thousands of feedbacks.

Learn and improve your coding skills like never before.

Try Programiz PRO
  • Interactive Courses
  • Certificates
  • AI Help
  • 2000+ Challenges