我有一个[Int]数组,我需要检查所有与另一个元素没有相同值的元素。我想要插入新数组的那些非相同元素。
########################################################################################
## create tables with summary statistic's###############################################
########################################################################################
setwd("C:/Data/nih/data/output/csv/merge") #choose destination folder
for (result in esc.micro@results){
print(as.character(result$areaid)) #print each file name into console as script runs
census.name <- as.character(result$areaid) #derive census tract from area ID
#create table for each census tract using summary statistics
table.unique <- c(mean(result$selection$BMI, na.rm = TRUE),sum(result$selection$female), sum(result$selection$male),
sum(result$selection$diabet),sum(result$selection$white), sum(result$selection$black),
sum(result$selection$indian), sum(result$selection$asian), sum(result$selection$pacific),
sum(result$selection$other), sum(result$selection$mixed))
table.unique <- c(census.name,table.unique) #combine census tract as column to summary stats
col.names <- c("areaID","BMI","female","male","diabet","white","black","indian","asian","pacific","other","mixed")
table.unique <- as.numeric(table.unique)
table.unique <-as.data.frame(t(table.unique)) #turn comlums into rows
names(table.unique) <- col.names #add column names
write.csv(table.unique, file = paste(census.name,".csv", sep='')) #write csv to output folder
}
#merge all files into single data frame
multmerge = function(mypath){
filenames=list.files(path=mypath, full.names=TRUE)
datalist = lapply(filenames, function(x){read.csv(file=x,header=TRUE)})
Reduce(function(x,y) {merge(x,y)}, datalist)
}
all.tracts <- multmerge("C:/Data/nih/data/output/csv/merge")
希望很清楚,谢谢
答案 0 :(得分:2)
这可以在一行中完成:
let numbers = [1, 1, 2, 3, 4, 4] // Here it is values 2,3
let uniques = Set(numbers).filter{ (n) in numbers.filter{$0==n}.count == 1 }
<强>更新强>
使用Swift 4,您还可以使用字典构造函数来执行此操作:
let uniques = Dictionary(grouping:numbers){$0}.filter{$1.count==1}.map{$0.0}
答案 1 :(得分:0)
你可以先检查一下你的数组中是否有多个数字,然后插入一个集合,否则追加该集合不包含它的元素:
let numbers = [1, 1, 2, 3, 4, 4] // Here it is values 2,3
var repeats: Set<Int> = []
var uniques: [Int] = []
for (index, number) in numbers.enumerated() {
if numbers[(numbers.index(index, offsetBy: 1, limitedBy: numbers.endIndex) ?? numbers.endIndex)..<numbers.endIndex].contains(number) {
repeats.insert(number)
} else if !repeats.contains(number) {
uniques.append(number)
}
}
uniques // 2,3
答案 2 :(得分:0)
我会使用2套:
var seenOnce: Set<Int> = []
var seenMorethanOnce: Set<Int> = []
let input = [1, 1, 2, 3, 4, 4]
for number in input
{
if seenMorethanOnce.contains(number)
{
// Skip it since it's already been detected as a dupe.
}
else if seenOnce.contains(number)
{
// We saw it once, and now we have a dupe.
seenOnce.remove(number)
seenMorethanOnce.insert(number)
}
else
{
// First time seeing this number.
seenOnce.insert(number)
}
}
当for循环结束时,seenOnce设置将包含您的值,如果您愿意,可以轻松地将其转换为数组。