R语言 检查指定名称的对象是否被定义 – exists() 函数
R编程语言 中的exists()函数 用于检查一个具有函数参数中指定名称的对象是否被定义。如果找到该对象,它将返回 TRUE。
语法: exists(name)
参数
- name: 要搜索的对象的名称
R语言中exists()函数的例子
例1:对变量应用exists()函数
# R program to check if
# an Object is defined or not
# Calling exists() function
exists("cos")
exists("diff")
exists("Hello")
输出
[1] TRUE
[1] TRUE
[1] FALSE
例2:对向量应用existence()函数
# 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()函数返回TRUE。这意味着exists()函数检查的是预先定义的和用户定义的,对象。
例3:检查数据框中的变量是否已被定义
# 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