모든 변수의 유형 가져오기
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
가변적일지라도.a
그리고.c
문자 변수가 아닙니다.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/Rscript에는 구체적인 데이터 유형이 없습니다.
R 인터프리터에는 오리형 메모리 할당 시스템이 있습니다.메모리에 대한 포인터의 데이터 유형을 알려주는 내장 메서드가 없습니다.오리 타이핑은 속도를 위해 수행되지만, 다음과 같은 문장이 있기 때문에 좋지 않은 것으로 판명되었습니다.print(is.integer(5))
FALSE를 반환합니다.is.integer(as.integer(5))
TRUE를 반환합니다.계산해 보세요.
기본 유형에 대한 R-매뉴얼: https://cran.r-project.org/doc/manuals/R-lang.html#Basic-types
여러분이 바랄 수 있는 최선의 방법은 메모리에 대한 포인터를 탐색하는 기능을 직접 작성한 다음 제거 프로세스를 사용하여 필요에 적합한지 여부를 결정하는 것입니다.
변수가 전역 또는 개체인 경우:
당신의.object()
로 침투해야 합니다.get(...)
눈 깜짝할 사이에예:
a <- 10
myGlobals <- objects()
for(i in myGlobals){
typeof(i) #prints character
typeof(get(i)) #prints integer
}
type of(...)는 메모리에 대한 변수 포인터를 시도합니다.
예를 들어, R 함수에는 최대 깊이에서 유형을 제공하는 편향이 있습니다.
library(tibble)
#expression notes type
#----------------------- -------------------------------------- ----------
typeof(TRUE) #a single boolean: logical
typeof(1L) #a single numeric with L postfixed: integer
typeof("foobar") #A single string in double quotes: character
typeof(1) #a single numeric: double
typeof(list(5,6,7)) #a list of numeric: list
typeof(2i) #an imaginary number complex
typeof(5 + 5L) #double + integer is coerced: double
typeof(c()) #an empty vector has no type: NULL
typeof(!5) #a bang before a double: logical
typeof(Inf) #infinity has a type: double
typeof(c(5,6,7)) #a vector containing only doubles: double
typeof(c(c(TRUE))) #a vector of vector of logicals: logical
typeof(matrix(1:10)) #a matrix of doubles has a type: list
typeof(substr("abc",2,2))#a string at index 2 which is 'b' is: character
typeof(c(5L,6L,7L)) #a vector containing only integers: integer
typeof(c(NA,NA,NA)) #a vector containing only NA: logical
typeof(data.frame()) #a data.frame with nothing in it: list
typeof(data.frame(c(3))) #a data.frame with a double in it: list
typeof(c("foobar")) #a vector containing only strings: character
typeof(pi) #builtin expression for pi: double
typeof(1.66) #a single numeric with mantissa: double
typeof(1.66L) #a double with L postfixed double
typeof(c("foobar")) #a vector containing only strings: character
typeof(c(5L, 6L)) #a vector containing only integers: integer
typeof(c(1.5, 2.5)) #a vector containing only doubles: double
typeof(c(1.5, 2.5)) #a vector containing only doubles: double
typeof(c(TRUE, FALSE)) #a vector containing only logicals: logical
typeof(factor()) #an empty factor has default type: integer
typeof(factor(3.14)) #a factor containing doubles: integer
typeof(factor(T, F)) #a factor containing logicals: integer
typeof(Sys.Date()) #builtin R dates: double
typeof(hms::hms(3600)) #hour minute second timestamp double
typeof(c(T, F)) #T and F are builtins: logical
typeof(1:10) #a builtin sequence of numerics: integer
typeof(NA) #The builtin value not available: logical
typeof(c(list(T))) #a vector of lists of logical: list
typeof(list(c(T))) #a list of vectors of logical: list
typeof(c(T, 3.14)) #a vector of logicals and doubles: double
typeof(c(3.14, "foo")) #a vector of doubles and characters: character
typeof(c("foo",list(T))) #a vector of strings and lists: list
typeof(list("foo",c(T))) #a list of strings and vectors: list
typeof(TRUE + 5L) #a logical plus an integer: integer
typeof(c(TRUE, 5L)[1]) #The true is coerced to 1 integer
typeof(c(c(2i), TRUE)[1])#logical coerced to complex: complex
typeof(c(NaN, 'batman')) #NaN's in a vector don't dominate: character
typeof(5 && 4) #doubles are coerced by order of && logical
typeof(8 < 'foobar') #string and double is coerced logical
typeof(list(4, T)[[1]]) #a list retains type at every index: double
typeof(list(4, T)[[2]]) #a list retains type at every index: logical
typeof(2 ** 5) #result of exponentiation double
typeof(0E0) #exponential lol notation double
typeof(0x3fade) #hexidecimal double
typeof(paste(3, '3')) #paste promotes types to string character
typeof(3 + 四) #R pukes on unicode error
typeof(iconv("a", "latin1", "UTF-8")) #UTF-8 characters character
typeof(5 == 5) #result of a comparison: logical
class(...)는 메모리에 대한 변수 포인터를 프로브합니다.
예를 들어, R 함수에는 유형을 캡슐화하는 컨테이너 또는 구조의 유형을 제공하는 편향이 있습니다.
library(tibble)
#expression notes class
#--------------------- ---------------------------------------- ---------
class(matrix(1:10)) #a matrix of doubles has a class: matrix
class(factor("hi")) #factor of items is: factor
class(TRUE) #a single boolean: logical
class(1L) #a single numeric with L postfixed: integer
class("foobar") #A single string in double quotes: character
class(1) #a single numeric: numeric
class(list(5,6,7)) #a list of numeric: list
class(2i) #an imaginary complex
class(data.frame()) #a data.frame with nothing in it: data.frame
class(Sys.Date()) #builtin R dates: Date
class(sapply) #a function is function
class(charToRaw("hi")) #convert string to raw: raw
class(array("hi")) #array of items is: array
class(5 + 5L) #double + integer is coerced: numeric
class(c()) #an empty vector has no class: NULL
class(!5) #a bang before a double: logical
class(Inf) #infinity has a class: numeric
class(c(5,6,7)) #a vector containing only doubles: numeric
class(c(c(TRUE))) #a vector of vector of logicals: logical
class(substr("abc",2,2))#a string at index 2 which is 'b' is: character
class(c(5L,6L,7L)) #a vector containing only integers: integer
class(c(NA,NA,NA)) #a vector containing only NA: logical
class(data.frame(c(3))) #a data.frame with a double in it: data.frame
class(c("foobar")) #a vector containing only strings: character
class(pi) #builtin expression for pi: numeric
class(1.66) #a single numeric with mantissa: numeric
class(1.66L) #a double with L postfixed numeric
class(c("foobar")) #a vector containing only strings: character
class(c(5L, 6L)) #a vector containing only integers: integer
class(c(1.5, 2.5)) #a vector containing only doubles: numeric
class(c(TRUE, FALSE)) #a vector containing only logicals: logical
class(factor()) #an empty factor has default class: factor
class(factor(3.14)) #a factor containing doubles: factor
class(factor(T, F)) #a factor containing logicals: factor
class(hms::hms(3600)) #hour minute second timestamp hms difftime
class(c(T, F)) #T and F are builtins: logical
class(1:10) #a builtin sequence of numerics: integer
class(NA) #The builtin value not available: logical
class(c(list(T))) #a vector of lists of logical: list
class(list(c(T))) #a list of vectors of logical: list
class(c(T, 3.14)) #a vector of logicals and doubles: numeric
class(c(3.14, "foo")) #a vector of doubles and characters: character
class(c("foo",list(T))) #a vector of strings and lists: list
class(list("foo",c(T))) #a list of strings and vectors: list
class(TRUE + 5L) #a logical plus an integer: integer
class(c(TRUE, 5L)[1]) #The true is coerced to 1 integer
class(c(c(2i), TRUE)[1])#logical coerced to complex: complex
class(c(NaN, 'batman')) #NaN's in a vector don't dominate: character
class(5 && 4) #doubles are coerced by order of && logical
class(8 < 'foobar') #string and double is coerced logical
class(list(4, T)[[1]]) #a list retains class at every index: numeric
class(list(4, T)[[2]]) #a list retains class at every index: logical
class(2 ** 5) #result of exponentiation numeric
class(0E0) #exponential lol notation numeric
class(0x3fade) #hexidecimal numeric
class(paste(3, '3')) #paste promotes class to string character
class(3 + 四) #R pukes on unicode error
class(iconv("a", "latin1", "UTF-8")) #UTF-8 characters character
class(5 == 5) #result of a comparison: logical
데이터 가져오기storage.mode
변수의:
R 변수가 디스크에 기록되면 데이터 레이아웃이 다시 변경되며 이를 데이터 레이아웃이라고 합니다.함수storage.mode(...)
에서는 R 개체의 모드, 클래스 및 유형을 참조하십시오.당신은 R의 스토리지에 대해 걱정할 필요가 없습니다.디스크에 데이터를 할당하고 읽을 때 발생하는 왕복 캐스트/제한으로 인한 지연을 이해하려고 하지 않는 한 모드로 전환할 수 있습니다.
데모: R/R 스크립트gettype(your_variable)
:
이 R 코드를 실행한 후 당신의 목적에 맞게 조정하면, 그것이 어떤 유형인지 꽤 잘 추측할 수 있을 것입니다.
get_type <- function(variable){
sz <- as.integer(length(variable)) #length of your variable
tof <- typeof(variable) #typeof your variable
cls <- class(variable) #class of your variable
isc <- is.character(variable) #what is.character() has to say about it.
d <- dim(variable) #dimensions of your variable
isv <- is.vector(variable)
if (is.matrix(variable)){
d <- dim(t(variable)) #dimensions of your matrix
}
#observations ----> datatype
if (sz>=1 && tof == "logical" && cls == "logical" && isv == TRUE){ return("vector of logical") }
if (sz>=1 && tof == "integer" && cls == "integer" ){ return("vector of integer") }
if (sz==1 && tof == "double" && cls == "Date" ){ return("Date") }
if (sz>=1 && tof == "raw" && cls == "raw" ){ return("vector of raw") }
if (sz>=1 && tof == "double" && cls == "numeric" ){ return("vector of double") }
if (sz>=1 && tof == "double" && cls == "array" ){ return("vector of array of double") }
if (sz>=1 && tof == "character" && cls == "array" ){ return("vector of array of character") }
if (sz>=0 && tof == "list" && cls == "data.frame" ){ return("data.frame") }
if (sz>=1 && isc == TRUE && isv == TRUE){ return("vector of character") }
if (sz>=1 && tof == "complex" && cls == "complex" ){ return("vector of complex") }
if (sz==0 && tof == "NULL" && cls == "NULL" ){ return("NULL") }
if (sz>=0 && tof == "integer" && cls == "factor" ){ return("factor") }
if (sz>=1 && tof == "double" && cls == "numeric" && isv == TRUE){ return("vector of double") }
if (sz>=1 && tof == "double" && cls == "matrix"){ return("matrix of double") }
if (sz>=1 && tof == "character" && cls == "matrix"){ return("matrix of character") }
if (sz>=1 && tof == "list" && cls == "list" && isv == TRUE){ return("vector of list") }
if (sz>=1 && tof == "closure" && cls == "function" && isv == FALSE){ return("closure/function") }
return("it's pointer to memory, bruh")
}
assert <- function(a, b){
if (a == b){
cat("P")
}
else{
cat("\nFAIL!!! Sniff test:\n")
sz <- as.integer(length(variable)) #length of your variable
tof <- typeof(variable) #typeof your variable
cls <- class(variable) #class of your variable
isc <- is.character(variable) #what is.character() has to say about it.
d <- dim(variable) #dimensions of your variable
isv <- is.vector(variable)
if (is.matrix(variable)){
d <- dim(t(variable)) #dimensions of your variable
}
if (!is.function(variable)){
print(paste("value: '", variable, "'"))
}
print(paste("get_type said: '", a, "'"))
print(paste("supposed to be: '", b, "'"))
cat("\nYour pointer to memory has properties:\n")
print(paste("sz: '", sz, "'"))
print(paste("tof: '", tof, "'"))
print(paste("cls: '", cls, "'"))
print(paste("d: '", d, "'"))
print(paste("isc: '", isc, "'"))
print(paste("isv: '", isv, "'"))
quit()
}
}
#these asserts give a sample for exercising the code.
assert(get_type(TRUE), "vector of logical") #everything is a vector in R by default.
assert(get_type(c(TRUE)), "vector of logical") #c() just casts to vector
assert(get_type(c(c(TRUE))),"vector of logical") #casting vector multiple times does nothing
assert(get_type(!5), "vector of logical") #bang inflicts 'not truth-like'
assert(get_type(1L), "vector of integer") #naked integers are still vectors of 1
assert(get_type(c(1L, 2L)), "vector of integer") #Longs are not doubles
assert(get_type(c(1L, c(2L, 3L))),"vector of integer") #nested vectors of integers
assert(get_type(c(1L, c(TRUE))), "vector of integer") #logicals coerced to integer
assert(get_type(c(FALSE, c(1L))), "vector of integer") #logicals coerced to integer
assert(get_type("foobar"), "vector of character") #character here means 'string'
assert(get_type(c(1L, "foobar")), "vector of character") #integers are coerced to string
assert(get_type(5), "vector of double")
assert(get_type(5 + 5L), "vector of double")
assert(get_type(Inf), "vector of double")
assert(get_type(c(5,6,7)), "vector of double")
assert(get_type(NaN), "vector of double")
assert(get_type(list(5)), "vector of list") #your list is in a vector.
assert(get_type(list(5,6,7)), "vector of list")
assert(get_type(c(list(5,6,7))),"vector of list")
assert(get_type(list(c(5,6),T)),"vector of list") #vector of list of vector and logical
assert(get_type(list(5,6,7)), "vector of list")
assert(get_type(2i), "vector of complex")
assert(get_type(c(2i, 3i, 4i)), "vector of complex")
assert(get_type(c()), "NULL")
assert(get_type(data.frame()), "data.frame")
assert(get_type(data.frame(4,5)),"data.frame")
assert(get_type(Sys.Date()), "Date")
assert(get_type(sapply), "closure/function")
assert(get_type(charToRaw("hi")),"vector of raw")
assert(get_type(c(charToRaw("a"), charToRaw("b"))), "vector of raw")
assert(get_type(array(4)), "vector of array of double")
assert(get_type(array(4,5)), "vector of array of double")
assert(get_type(array("hi")), "vector of array of character")
assert(get_type(factor()), "factor")
assert(get_type(factor(3.14)), "factor")
assert(get_type(factor(TRUE)), "factor")
assert(get_type(matrix(3,4,5)), "matrix of double")
assert(get_type(as.matrix(5)), "matrix of double")
assert(get_type(matrix("yatta")),"matrix of character")
저는 여기에 C++/Java/Python 이데올로기를 넣었습니다. 이것은 제게 기억이 가장 어떻게 생겼는지에 대한 특종을 제공합니다.트라이애드 타이핑 시스템은 스파게티를 벽에 못박는 것과 같습니다.<-
그리고.<<-
가장 의심이 가지 않을 때 목록에 행렬을 패키지화합니다. 입니다.오리처럼 뒤뚱거리면 오리처럼 꽥꽥거리고 깃털이 있다면 오리입니다.
클래스(x)를 사용하여 변수 유형을 확인할 수 있습니다.데이터 프레임의 모든 변수 유형을 확인해야 하는 경우 apply(x, class)를 사용할 수 있습니다.
> mtcars %>%
+ summarise_all(typeof) %>%
+ gather
key value
1 mpg double
2 cyl double
3 disp double
4 hp double
5 drat double
6 wt double
7 qsec double
8 vs double
9 am double
10 gear double
11 carb double
나는 노력한다class
그리고.typeof
기능은 있지만 모두 실패합니다.
기본적으로 원하는 것과 반대로 설계된 제 툴킷 장난감 중 하나는 다음과 같습니다.
lstype<-function(type='closure'){
inlist<-ls(.GlobalEnv)
if (type=='function') type <-'closure'
typelist<-sapply(sapply(inlist,get),typeof)
return(names(typelist[typelist==type]))
}
lapply(your_dataframe, 클래스)는 다음과 같은 것을 제공합니다.
$159r [1] "인자"
$날짜 [1] "날짜"
$열림 [1] "숫자"
$ 높음 [1] "숫자"
...기타.
언급URL : https://stackoverflow.com/questions/12693908/get-type-of-all-variables
'sourcetip' 카테고리의 다른 글
R(루프)에서 리스트에 요소를 추가하는 방법 (0) | 2023.07.02 |
---|---|
C에서 포인터가 이미 해제되었는지 어떻게 확인합니까? (0) | 2023.07.02 |
Oracle에서 JDK 버전을 확인하는 방법은 무엇입니까? (0) | 2023.07.02 |
2d 배열은 이중 포인터입니까? (0) | 2023.07.02 |
파티션 기준 절이 있는 ROW_NUMBER()가 Maria에서 작동을 중지했습니다.DB (0) | 2023.07.02 |