2017-09-22 3 views
1

나는 약 40 열의 큰 data.table을 가지고 있으며, 나머지 열은 단지 NA 일뿐입니다. 재현 예를하려면 :NA 값을 갖는 데이터 바인딩 목록 작성

require(data.table) 
data(iris) 
setDT(iris) 

# this works (and is the expected result): 
rbind(iris, list(6, NA, NA, NA, "test")) 

문제는 내가 37+ 빈 열 (I는 입력 할 데이터가 변수의 1, 2 및 37 컬럼에있다)가있다. 그래서 rep 중 일부는 NA 중 일부입니다. 하지만 시도하면 :

rbind(iris, list(6, rep(NA, 3), "test")) 

작동하지 않습니다 (크기가 다릅니다). 할 수있다

rbind(iris, list(c(6, rep(NA, 3), "test"))) 

그러나 (분명히) 전체 첫 번째 열을 char로 강제 변환합니다. 나는 목록을 목록에서 없애고, list(c( 시퀀스를 반전 (목록 만 허용)하고 아직 아무것도 찾지 못했습니다.

rbind 데이터 테이블에 대한 (여러) 게시물의 복제본이 아닙니다. 필자는 그렇게 할 수 있습니다. 내가 할 수 없었던 것은 을 사용하면서 적절한 데이터 클래스를 유지하는 것이다. rep(NA, x)을 사용한다.

답변

3

당신이 할 수있는 ...

rbind(data.table(iris), c(list(6), logical(3), list("test"))) 

    Sepal.Length Sepal.Width Petal.Length Petal.Width Species 
    1:   5.1   3.5   1.4   0.2 setosa 
    2:   4.9   3.0   1.4   0.2 setosa 
    3:   4.7   3.2   1.3   0.2 setosa 
    4:   4.6   3.1   1.5   0.2 setosa 
    5:   5.0   3.6   1.4   0.2 setosa 
---                
147:   6.3   2.5   5.0   1.9 virginica 
148:   6.5   3.0   5.2   2.0 virginica 
149:   6.2   3.4   5.4   2.3 virginica 
150:   5.9   3.0   5.1   1.8 virginica 
151:   6.0   NA   NA   NA  test 

logical(n)rep(NA, n)과 동일합니다. irisdata.table()에 감쌌으므로 rbind.data.frame 대신 rbindlist이 사용되고 "test"은 잘못된 수준이 아닌 새로운 요인 수준으로 처리됩니다.


내가 좋아하는,하지만가는 더 나은 방법이 있다고 생각 ...

newrow = setDT(iris[NA_integer_, ]) 
newrow[, `:=`(Sepal.Length = 6, Species = factor("test")) ] 
rbind(data.table(iris), newrow) 

# or 

rbind(data.table(iris), list(Sepal.Length = 6, Species = "test"), fill=TRUE) 

이러한 접근은 명확하고 열 계산 손보는 필요하지 않습니다.

나는 데이터 변환을 검토하기 위해 검사 할 수있는 테이블을 남기 때문에 newrow 방식을 선호합니다. (1) (`data.table (아이리스) [C :

+0

또 너무 영리 별 반 아이디어를 댓글 수 : (N, NA)] [N, \': = \ '(Sepal.Length = 6, Species = factor ("test"))] []' – Frank

2

우리는 replicate

rbind(iris, c(6, replicate(3, NA, simplify = FALSE), "test")) 
# Sepal.Length Sepal.Width Petal.Length Petal.Width Species 
# 1:   5.1   3.5   1.4   0.2 setosa 
# 2:   4.9   3.0   1.4   0.2 setosa 
# 3:   4.7   3.2   1.3   0.2 setosa 
# 4:   4.6   3.1   1.5   0.2 setosa 
# 5:   5.0   3.6   1.4   0.2 setosa 
# ---                
#147:   6.3   2.5   5.0   1.9 virginica 
#148:   6.5   3.0   5.2   2.0 virginica 
#149:   6.2   3.4   5.4   2.3 virginica 
#150:   5.9   3.0   5.1   1.8 virginica 
#151:   6.0   NA   NA   NA  test 

를 사용하거나 @Frank로

rbind(iris, c(6, as.list(rep(NA, 3)), "test")) 
관련 문제