Find last occurrence of a data frame in R
Last Updated :
26 Mar, 2024
In this article, we will explore various methods to find the last occurrence in a data frame by using the R Programming Language.
R language offers various methods to find the last occurrence in a data frame. By using these methods provided by R, it is possible to find every occurrence. Some of the methods to find the last occurrence are:
Find the last occurrence in the data frame By using the ‘tail()’ function
It is a method, that can find every occurrence in a data frame. In this example, we created a data frame and found the last occurrence of it.
R
#creating data frame
df <- data.frame(
Name= c("A", "B", "C", "D", "E", "F"),
Age= c(8,7,6,5,3,2)
)
print(df)
print("The last occurrence is")
# Finding the last occurrence of a specific element
tail(df,1)
Output:
Name Age
1 A 8
2 B 7
3 C 6
4 D 5
5 E 3
6 F 2
[1] "The last occurrence is"
Name Age
6 F 2
In this example, we created a dataframe and finded the last occurrence of it.
R
ID= c(8,7,6,5,3,2)
Name= c("Ravi", "Rakesh", "Suresh", "Naresh", "Lokesh", "Sukesh")
df <- data.frame(ID,Name)
print(df)
# Finding the last occurrence of a specific element
print("The last occurrence is")
tail(df,1)
Output:
ID Name
1 8 Ravi
2 7 Rakesh
3 6 Suresh
4 5 Naresh
5 3 Lokesh
6 2 Sukesh
[1] "The last occurrence is"
ID Name
6 2 Sukesh
Find last occurrence in data frame By using the ‘which.max()’ function
It is method, that have ability to find every occurrence in a data frame. In this example, we created a dataframe and finded the last occurrence of it.
R
# Creating data frame
df <- data.frame(Name= c("A","B","C","D","E"),
Age = c(25,35,45,30, 40))
print(df)
# Finding the last occurrence
last_index <- which.max(df$Age == 40)
print("The last occurence is")
res <- df[last_index, ]
res
Output:
Name Age
1 A 25
2 B 35
3 C 45
4 D 30
5 E 40
[1] "The last occurence is"
Name Age
5 E 40
In this example, we created a dataframe and finded the last occurrence of it.
R
Name= c("Ravi","Rakesh","Karim","Kavya","sakesh", "Ramya")
ID = c(25,35,45,23,29,42)
df <- data.frame(Name, ID)
print(df)
# Finding the last occurrence
last_index <- which.max(df$ID == 42)
print("The last occurence is")
res <- df[last_index, ]
res
Output:
Name ID
1 Ravi 25
2 Rakesh 35
3 Karim 45
4 Kavya 23
5 sakesh 29
6 Ramya 42
[1] "The last occurence is"
Name ID
6 Ramya 42
Conclusion
In conclusion, we learned about how to find the last occurrence of a data frame by using various methods. R languages provides various functions while dealing with the last occurence.
Share your thoughts in the comments
Please Login to comment...