我有一个包含给定股票月度回报的大数据集。我想删除没有全年数据的行。下面显示了一个数据子集作为示例:
import UIKit
import WebKit
class SearchCollectionViewCell: UICollectionViewCell {
@IBOutlet weak var webView: UIWebView!
@IBOutlet weak var spinner: UIActivityIndicatorView!
func webViewDidStartLoad(_ webView: UIWebView) {
print("we're loading")
}
}
理想情况下,代码将删除前四个观察结果,因为它们没有一整年的观察结果。
答案 0 :(得分:1)
OP要求从月度值的大数据集中删除所有行,这些数据集不构成一整年。虽然solution suggested by Wen似乎是working for the OP,但我想建议一种更强大的方法。
Wen的解决方案计算每年的行数,假设每月只有一行。如果生产数据集中存在重复条目,则每年计算唯一月数会更加健壮。 (根据我的经验,在处理生产数据和检查所有假设时,人们不够小心。)
library(data.table)
# count number of unique months per year,
# keep only complete years, omit counts
# result is a data.table with one column Year
full_years <- DT[, uniqueN(month(Date)), by = Year][V1 == 12L, -"V1"]
full_years
Year 1: 2010
# right join with original table, only rows belonging to a full year will be returned
DT[full_years, on = "Year"]
Date Return Year 1: 2010-01-01 0.83293 2010 2: 2010-02-01 0.18279 2010 3: 2010-03-01 0.19416 2010 4: 2010-04-01 0.38907 2010 5: 2010-05-01 0.37834 2010 6: 2010-06-01 0.64010 2010 7: 2010-07-01 0.62079 2010 8: 2010-08-01 0.42128 2010 9: 2010-09-01 0.43117 2010 10: 2010-10-01 0.42307 2010 11: 2010-11-01 -0.19940 2010 12: 2010-12-01 -0.22520 2010
请注意,此方法可避免向可能较大的数据集的每一行添加count
列。
代码可以更简洁地写成:
DT[DT[, uniqueN(month(Date)), by = Year][V1 == 12L, -"V1"], on = "Year"]
也可以检查任何重复月份的数据,例如,
stopifnot(all(DT[, .N, by = .(Year, month(Date))]$N == 1L))
此代码计算每年和每月的出现次数,并在有多个时停止执行。