일부 데이터를 병합 한 후 ID 당 여러 행이 있습니다. 데이터가 다른 경우에만 여러 개의 동일한 ID를 유지하고 싶습니다. NA
값 colwise 모든 데이터 포인트와 동일한 것으로 간주한다.
df <- structure(list(id = c(1L, 2L, 2L, 2L, 3L, 3L, 4L, 4L, 4L, 5L),
v1 = structure(c(1L, 1L, NA, 1L, 1L, 1L, 1L, NA, 1L, 1L), .Label = "a", class = "factor"),
v2 = structure(c(1L, 2L, 2L, 3L, 1L, 1L, 1L, 1L, NA, 1L), .Label = c("a",
"b", "c"), class = "factor"), v3 = structure(c(1L, 1L, 1L,
1L, 1L, 1L, NA, 2L, 2L, 1L), .Label = c("a", "b"), class = "factor")), .Names = c("id",
"v1", "v2", "v3"), row.names = c(NA, -10L), class = "data.frame")
id v1 v2 v3
1 a a a
2 a b a
2 <NA> b a
2 a c a
3 a a a
3 a a a
4 a a <NA>
4 <NA> a b
4 a <NA> b
5 a a a
id v1 v2 v3
1 a a a
2 a b a
2 a c a
3 a a a
4 a a b
5 a a a
data.table
해결책 이 있으면 행복합니다 .
data.table
-package를 사용하는 가능한 솔루션 :
library(data.table)
setDT(df)[, lapply(.SD, function(x) unique(na.omit(x))), by = id]
다음을 제공합니다.
id v1 v2 v3 1: 1 a a a 2: 2 a b a 3: 2 a c a 4: 3 a a a 5: 4 a a b 6: 5 a a a
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다