# 数据表中变量的唯一Ob数Number of Unique Obs by Variable in a Data Table

``````data <- as.data.set(spss.system.file(paste(path, file, sep = '/')))
``````

``````require(data.table)

### Create a data.table
dt <- data.table(a = 1:10,
b = letters[1:10],
c = rep(1, times = 10))

### Create a comparable data.frame
df <- data.frame(dt)

### Expected result
unique(dt\$a)

### Expected result
length(unique(dt\$a))
``````

``````### I want to determine the number of unique obs in
# each variable, for a large list of vars
lapply(names(df), function(x) {
length(unique(df[, x]))
})

### Unexpected result
length(unique(dt[, 'a', with = F]))  # Returns 1
``````

``````dt[, 'a', with = F]
``````

``````for (x in names(data)) {
unique.obs <- length(unique(data[, x]))
if (unique.obs == 1) {
data[, x] <- NULL
}
}
``````

# 更新： `uniqueN`

``````dt[ , lapply(.SD, uniqueN)]
``````

`````` dt[, lapply(.SD, function(x) length(unique(x)))]
##     a  b c
## 1: 10 10 1
``````

``````lapply(names(df) function(x) length(unique(dt[, x, with = FALSE])))
``````

`````` lapply(names(df) function(x) length(unique(dt[[x]])))
``````

``````dt[,names(dt) := lapply(.SD, function(x) if(length(unique(x)) ==1) {return(NULL)} else{return(x)})]

# or to avoid calling `.SD`

dt[, Filter(names(dt), f = function(x) length(unique(dt[[x]]))==1) := NULL]
``````

### ===============>>#2 票数：3

``````for (i in names(DT)) if (length(unique(DT[[i]]))==1) DT[,(i):=NULL]
``````

``````for (i in ncol(DT):1) if (length(unique(DT[[i]]))==1) DT[,(i):=NULL]
``````

### ===============>>#3 票数：1

``````require(data.table)

### Create a data.table
dt <- data.table(a = 1:10,
b = letters[1:10],
d1 = "",
c = rep(1, times = 10),
d2 = "")
dt
a b d1 c d2
1:  1 a    1
2:  2 b    1
3:  3 c    1
4:  4 d    1
5:  5 e    1
6:  6 f    1
7:  7 g    1
8:  8 h    1
9:  9 i    1
10: 10 j    1
``````

``````only_space <- function(x) {
length(unique(x))==1 && x[1]==""
}
bolCols <- apply(dt, 2, only_space)
dt[, (1:ncol(dt))[!bolCols], with=FALSE]
``````

``````     a b c
1:  1 a 1
2:  2 b 1
3:  3 c 1
4:  4 d 1
5:  5 e 1
6:  6 f 1
7:  7 g 1
8:  8 h 1
9:  9 i 1
10: 10 j 1
``````

### ===============>>#4 票数：0

newdata < - select（old_data，第一个变量，第二个变量）