gpt4 book ai didi

r - 获取所有变量的类型

转载 作者:行者123 更新时间:2023-12-03 04:39:55 26 4
gpt4 key购买 nike

在 R 中,我想在脚本末尾检索全局变量列表并迭代它们。这是我的代码

#declare a few sample variables
a<-10
b<-"Hello world"
c<-data.frame()

#get all global variables in script and iterate over them
myGlobals<-objects()
for(i in myGlobals){
print(typeof(i)) #prints 'character'
}

我的问题是 typeof(i) 总是返回 character 即使变量 ac 不是字符变量。如何获取for循环内变量的原始类型?

最佳答案

您需要使用get来获取值,而不是ls返回的对象的字符名称:

x <- 1L
typeof(ls())
[1] "character"
typeof(get(ls()))
[1] "integer"

或者,对于所提出的问题,您可能需要使用eapply:

eapply(.GlobalEnv,typeof)
$x
[1] "integer"

$a
[1] "double"

$b
[1] "character"

$c
[1] "list"

关于r - 获取所有变量的类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12693908/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com