检查R编程中是否定义了指定名称的对象-exists()函数
R 编程语言中的exists()函数用于检查函数参数中指定名称的对象是否已定义。如果找到对象,则返回 TRUE。
Syntax: exists(name)
Parameters:
- name: Name of the Object to be searched
R语言示例中的exists()函数
示例 1:将 exists()函数应用于变量
R
# R program to check if
# an Object is defined or not
# Calling exists() function
exists("cos")
exists("diff")
exists("Hello")
R
# R program to check if
# an Object is defined or not
# Creating a vector
Hello <- c(1, 2, 3, 4, 5)
# Calling exists() function
exists("Hello")
R
# R program to create dataframe
# and apply exists function
# creating a data frame
friend.data <- data.frame(
friend_id = c(1:5),
friend_name = c("Sachin", "Sourav",
"Dravid", "Sehwag",
"Dhoni"),
stringsAsFactors = FALSE
)
# print the data frame
print(friend.data)
attach(friend.data)
exists('friend_id')
输出:
[1] TRUE
[1] TRUE
[1] FALSE
示例 2:将 exists()函数应用于 Vector
R
# R program to check if
# an Object is defined or not
# Creating a vector
Hello <- c(1, 2, 3, 4, 5)
# Calling exists() function
exists("Hello")
输出:
[1] TRUE
在上面的例子中可以看出,当第一个代码中没有定义名为“Hello”的对象时,exists()函数返回了FALSE,而在声明了“Hello”对象之后,exists()函数返回了真的。这意味着 exists()函数检查预定义和用户定义的对象。
示例 3:检查数据框中的变量是否已定义
R
# R program to create dataframe
# and apply exists function
# creating a data frame
friend.data <- data.frame(
friend_id = c(1:5),
friend_name = c("Sachin", "Sourav",
"Dravid", "Sehwag",
"Dhoni"),
stringsAsFactors = FALSE
)
# print the data frame
print(friend.data)
attach(friend.data)
exists('friend_id')
输出:
friend_id friend_name
1 1 Sachin
2 2 Sourav
3 3 Dravid
4 4 Sehwag
5 5 Dhoni
TRUE