data.frame 또는 행렬을 사용해야합니까?
언제을 사용해야하고 언제을 사용하는 data.frame
것이 더 낫 matrix
습니까?
둘 다 데이터를 직사각형 형식으로 유지하기 때문에 때때로 불분명합니다.
언제 어떤 데이터 유형을 사용해야하는지에 대한 일반적인 규칙이 있습니까?
답변의 일부는 이미 귀하의 질문에 포함되어 있습니다 : 열 (변수)이 다른 유형 (숫자 / 문자 / 논리 등) 일 것으로 예상되는 경우 데이터 프레임을 사용하십시오. 행렬은 같은 유형의 데이터를위한 것입니다.
결과적으로, matrix / data.frame 선택은 동일한 유형의 데이터가있는 경우에만 문제가됩니다.
답은 data.frame / matrix의 데이터로 수행하려는 작업에 따라 다릅니다. 다른 함수로 전달 될 경우 이러한 함수의 예상 인수 유형이 선택을 결정합니다.
또한:
행렬은 더 메모리 효율적입니다.
m = matrix(1:4, 2, 2)
d = as.data.frame(m)
object.size(m)
# 216 bytes
object.size(d)
# 792 bytes
선형 대수 유형의 연산을 수행하려는 경우 행렬이 필요합니다.
데이터 프레임은 이름으로 열을 자주 참조하는 경우 (콤팩트 $ 연산자를 통해) 더 편리합니다.
각 열에 개별적으로 서식을 적용 할 수 있으므로 테이블 형식 정보를보고 (인쇄)하는 데 데이터 프레임이 더 좋습니다.
@Michal이 언급하지 않은 것은 동등한 데이터 프레임보다 작은 매트릭스 일뿐 만 아니라 행렬을 사용하면 데이터 프레임을 사용하는 것보다 훨씬 효율적으로 코드를 훨씬 효율적으로 만들 수 있다는 것입니다. 이것이 내부적으로 많은 R 함수가 데이터 프레임에있는 행렬 데이터로 강제되는 이유입니다.
데이터 프레임은 종종 훨씬 더 편리합니다. 항상 원자 적으로 만 존재하는 것은 아닙니다.
문자 행렬을 가질 수 있습니다. R로 행렬을 만들기 위해 숫자 데이터를 가질 필요는 없습니다.
데이터 프레임을 행렬 data.matrix()
로 변환 할 때는 내부 수준에 따라 요소를 숫자 값으로 변환하여 적절히 처리 하는 함수 가 있습니다. as.matrix()
인자 레이블이 숫자가 아닌 경우 비아 를 강제 변환 하면 문자 행렬이 생성됩니다. 비교:
> head(as.matrix(data.frame(a = factor(letters), B = factor(LETTERS))))
a B
[1,] "a" "A"
[2,] "b" "B"
[3,] "c" "C"
[4,] "d" "D"
[5,] "e" "E"
[6,] "f" "F"
> head(data.matrix(data.frame(a = factor(letters), B = factor(LETTERS))))
a B
[1,] 1 1
[2,] 2 2
[3,] 3 3
[4,] 4 4
[5,] 5 5
[6,] 6 6
나는 종종 숫자 변수 이상을 가지고 있기 때문에 거의 항상 데이터 분석 작업에 데이터 프레임을 사용합니다. 패키지의 함수를 코딩 할 때는 거의 항상 행렬로 강제 변환 한 다음 결과를 데이터 프레임으로 다시 형식화합니다. 데이터 프레임이 편리하기 때문입니다.
@Michal : 행렬은 실제로 더 효율적인 메모리는 아닙니다.
m <- matrix(1:400000, 200000, 2)
d <- data.frame(m)
object.size(m)
# 1600200 bytes
object.size(d)
# 1600776 bytes
... 열 수가 많은 경우가 아니면 :
m <- matrix(1:400000, 2, 200000)
d <- data.frame(m)
object.size(m)
# 1600200 bytes
object.size(d)
# 22400568 bytes
The matrix is actually a vector with additional methods. while data.frame is a list. The difference is down to vector vs list. for computation efficiency, stick with matrix. Using data.frame if you have to.
Matrices and data frames are rectangular 2D arrays and can be heterogeneous by rows and columns. They share some methods and properties, but not all.
Examples:
M <- list(3.14,TRUE,5L,c(2,3,5),"dog",1i) # a list
dim(M) <- c(2,3) # set dimensions
print(M) # print result
# [,1] [,2] [,3]
# [1,] 3.14 5 "dog"
# [2,] TRUE Numeric,3 0+1i
DF <- data.frame(M) # a data frame
print(DF) # print result
# X1 X2 X3
# 1 3.14 5 dog
# 2 TRUE 2, 3, 5 0+1i
M <- matrix(c(1,1,1,1,2,3,1,3,6),3) # a numeric matrix
DF <- data.frame(M) # a all numeric data frame
solve(M) # obtains inverse matrix
solve(DF) # obtains inverse matrix
det(M) # obtains determinant
det(DF) # error
I cannot stress out more the efficiency difference between the two! While it is true that DFs are more convenient in some especially data analysis cases, they also allow heterogeneous data, and some libraries accept them only, these all is really secondary unless you write a one-time code for a specific task.
Let me give you an example. There was a function that would calculate the 2D path of the MCMC method. Basically, this means we take an initial point (x,y), and iterate a certain algorithm to find a new point (x,y) at each step, constructing this way the whole path. The algorithm involves calculating a quite complex function and the generation of some random variable at each iteration, so when it run for 12 seconds I thought it is fine given how much stuff it does at each step. That being said, the function collected all points in the constructed path together with the value of an objective function in a 3-column data.frame. So, 3 columns is not that large, and the number of steps was also more than reasonable 10,000 (in this kind of problems paths of length 1,000,000 are typical, so 10,000 is nothing). So, I thought a DF 10,000x3 is definitely not an issue. The reason a DF was used is simple. After calling the function, ggplot() was called to draw the resulting (x,y)-path. And ggplot() does not accept a matrix.
Then, at some point out of curiosity I decided to change the function to collect the path in a matrix. Gladly the syntax of DFs and matrices is similar, all I did was to change the line specifying df as a data.frame to one initializing it as a matrix. Here I need also to mention that in the initial code the DF was initialized to have the final size, so later in the code of the function only new values were recorded into already allocated spaces, and there was no overhead of adding new rows to the DF. This makes the comparison even more fair, and it also made my job simpler as I did not need to rewrite anything further in the function. Just one line change from the initial allocation of a data.frame of the required size to a matrix of the same size. To adapt the new version of the function to ggplot(), I converted the now returned matrix to a data.frame to use in ggplot().
After I rerun the code I could not believe the result. The code run in a fraction of a second! Instead of about 12 seconds. And again, the function during the 10,000 iterations only read and wrote values to already allocated spaces in a DF (and now in a matrix). And this difference is also for the reasonable (or rather small) size 10000x3.
So, if your only reason to use a DF is to make it compatible with a library function such as ggplot(), you can always convert it to a DF at the last moment -- work with matrices as far as you feel convenient. If on the other hand there is a more substantial reason to use a DF, such as you use some data analysis package that would require otherwise constant transforming from matrices to DFs and back, or you do not do any intensive calculations yourself and only use standard packages (many of them actually internally transform a DF to a matrix, do their job, and then transform the result back -- so they do all efficiency work for you), or do a one-time job so you do not care and feel more comfortable with DFs, then you should not worry about efficiency.
Or a different more practical rule: if you have a question such as in the OP, use matrices, so you would use DFs only when you do not have such a question (because you already know you have to use DFs, or because you do not really care as the code is one-time etc.).
But in general keep this efficiency point always in mind as a priority.
참고URL : https://stackoverflow.com/questions/5158790/should-i-use-a-data-frame-or-a-matrix
'IT story' 카테고리의 다른 글
Android LocationClient 클래스는 더 이상 사용되지 않지만 설명서에서 사용됩니다. (0) | 2020.06.12 |
---|---|
geom_point의 포인트 레이블 (0) | 2020.06.12 |
JavaScript / jQuery에서 객체를 쿼리 문자열로 직렬화 (0) | 2020.06.12 |
배열에 다른 배열의 값이 포함되어 있습니까? (0) | 2020.06.12 |
Git을 사용하여 로컬과 원격 사이의 변화를 어떻게 찾을 수 있습니까? (0) | 2020.06.12 |