我是循环新手。我有一个笨重的数据框架,我想减少,以便只保留没有负数的观察(行)。这就是我被困的地方。这样每次都会创建一个空值而不是精简的数据框。
button.setIcon(new ImageIcon(buttonImg.getScaledInstance(15, 15, Image.SCALE_SMOOTH)));
答案 0 :(得分:6)
纯粹的矢量化解决方案怎么样:
DF[!rowSums(DF < 0), ]
# ID Items Sequence
#1 1 D 1
#2 1 A 2
#5 2 B 2
数据
DF=structure(list(ID = c(1, 1, 1, -1, 2), Items = c("D", "A", "A",
"A", "B"), Sequence = c(1, 2, -2, 1, 2)), .Names = c("ID", "Items",
"Sequence"), row.names = c(NA, -5L), class = "data.frame")
<强>解释强>
比较DF < 0
为data.frame
TRUE/FALSE
DF < 0
# ID Items Sequence
# [1,] FALSE FALSE FALSE
# [2,] FALSE FALSE FALSE
# [3,] FALSE FALSE TRUE
# [4,] TRUE FALSE FALSE
# [5,] FALSE FALSE FALSE
rowSums()
然后给我们每行的总和(作为TRUE == 1, FALSE == 0
)
rowSums(DF<0)
# [1] 0 0 1 1 0
因此我们可以使用此向量来对data.frame进行子集化。但是,因为我们想要它的值都是正值(即rowSums == 0),我们否定过滤器
DF[!rowSums(DF < 0), ]
答案 1 :(得分:3)
你不需要循环:)
DF=structure(list(ID = c(1, 1, 1, -1, 2), Items = c("D", "A", "A",
"A", "B"), Sequence = c(1, 2, -2, 1, 2)), .Names = c("ID", "Items",
"Sequence"), row.names = c(NA, -5L), class = "data.frame")
DF
# ID Items Sequence
#1 1 D 1
#2 1 A 2
#3 1 A -2
#4 -1 A 1
#5 2 B 2
new_DF = DF[apply(DF<0,1,function(x) !any(x)),]
new_DF
# ID Items Sequence
#1 1 D 1
#2 1 A 2
#5 2 B 2