Open In App

Create a dataframe in R with different number of rows

Last Updated : 16 Apr, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

In this article, we will explore how to create a data frame with different numbers of rows by using the R Programming Language.

How do we create the data frame?

data. frame() is a function that is used to create the data frame. By using these functions provided by R, it is possible to create the data frame easily. Some of the examples of creating the data frame with different numbers of rows are:

In the below example, we created the data frame with 4 rows by using the function ‘data. frame()’.

R
names = c("Alice", "Bob", "Charlie", "David")
ages = c(25, 30, 35, 40)
cities = c("New York", "Los Angeles", "Chicago", "Houston")
salaries = c(50000, 60000, 70000, 80000)

print("creating data frame with 4 rows")
result=data.frame(names,ages, cities, salaries)
print(result)

Output:

[1] "creating data frame with 4 rows"

names ages cities salaries
1 Alice 25 New York 50000
2 Bob 30 Los Angeles 60000
3 Charlie 35 Chicago 70000
4 David 40 Houston 80000

Now we create the data frame with 7 rows by using the function ‘data.frame()’.

R
#creating data frame
df = data.frame( rno=c(1:7),
                 id=11:17,
                Age =c(21, 22, 23, 24, 25, 26, 27),
                years =31:37)
print("creating data frame with 7 rows")
print(df)

Output:

[1] "creating data frame with 7 rows"

rno id Age years
1 1 11 21 31
2 2 12 22 32
3 3 13 23 33
4 4 14 24 34
5 5 15 25 35
6 6 16 26 36
7 7 17 27 37

In the below example, we created the data frame with 10 rows by using the function ‘data.frame()’.

R
# Creating dataframe 
data = data.frame(
  ID = 1:10, 
  Name = c("John", "Alice", "Bob", "Emily", "David", "Sophia", "Michael", 
            "Emma", "Daniel", "Olivia"),  
  Age = c(25, 30, 22, 35, 28, 27, 40, 33, 29, 31), 
  Gender = c("M", "F", "M", "F", "M", "F", "M", "F", "M", "F"),  
  stringsAsFactors = FALSE
               )
print("creating data frame with 10 rows")
print(data)

Output:

[1] "creating data frame with 10 rows"

ID Name Age Gender
1 1 John 25 M
2 2 Alice 30 F
3 3 Bob 22 M
4 4 Emily 35 F
5 5 David 28 M
6 6 Sophia 27 F
7 7 Michael 40 M
8 8 Emma 33 F
9 9 Daniel 29 M
10 10 Olivia 31 F

Conclusion

In conclusion, we learned about how to create a dataframe with different number of rows using R. R language offers versatile tools while dealing with data frames.



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads