B.Sc Computer Science
R Programming - Lab
Bharathiar University
Program 4
Data Frames in R
Program 4- Write a R program to perform various operations in data frame
SOURCE CODE:
# R program for dataframe
# A vector which is a character vector
name = c("Ram", "Raja", "Rani")
# A vector which is a character vector
subject = c("R", "Python", "Java")
# A vector which is a numeric vector
mark = c(64, 72, 80)
df = data.frame(name, subject, mark)
print(df)
# Accessing first and second row
print("Accessing first and second row\n")
print(df[1:2, ])
# Accessing first and second column
print("Accessing first and second column\n")
print(df[, 1:2])
print("Before adding row\n")
print(df)
# Add a new row using rbind()
newDf = rbind(df, data.frame(name = "deepa",
subject = "C",
mark = 75
))
print("After Added a row\n")
print(newDf)
print("Before adding column\n")
print(df)
# Add a new column using cbind()
newDf = cbind(df, rank=c(3, 5, 1))
print("After Added a column\n")
print(newDf)
print("Before deleting the 3rd row and 2nd column\n")
print(df)
# delete the third row and the second column
newDF = df[-3, -2]
print("After Deleted the 3rd row and 2nd column\n")
print(newDF)
OUTPUT:
name subject mark
1 Ram R 64
2 Raja Python 72
3 Rani Java 80
[1] "Accessing first and second row\n"
name subject mark
1 Ram R 64
2 Raja Python 72
[1] "Accessing first and second column\n"
name subject
1 Ram R
2 Raja Python
3 Rani Java
[1] "Before adding row\n"
name subject mark
1 Ram R 64
2 Raja Python 72
3 Rani Java 80
[1] "After Added a row\n"
name subject mark
1 Ram R 64
2 Raja Python 72
3 Rani Java 80
4 deepa C 75
[1] "Before adding column\n"
name subject mark
1 Ram R 64
2 Raja Python 72
3 Rani Java 80
[1] "After Added a column\n"
name subject mark rank
1 Ram R 64 3
2 Raja Python 72 5
3 Rani Java 80 1
[1] "Before deleting the 3rd row and 2nd column\n"
name subject mark
1 Ram R 64
2 Raja Python 72
3 Rani Java 80
[1] "After Deleted the 3rd row and 2nd column\n"
name mark
1 Ram 64
2 Raja 72
|
No comments:
Post a Comment