如何使用循环删除R中所有带有负值的行 [英] How to use a loop to delete all rows with negative values in R
问题描述
我是新手.我有一个笨拙的数据框,我想减少它,以便仅保留没有负数的观测值(行).这是我卡住的地方.每次都会创建一个空值,而不是修剪后的数据帧.
I am new to loops. I have an unwieldy data frame that I want to cut down so that only observations (rows) without negative numbers remain. Here is where I'm stuck. This creates a null value every time instead of a trimmed down data frame.
mydata=for (i in names(df)) {
subset(df, df[[ paste(i)]]>=0)
}
推荐答案
纯矢量化解决方案如何:
How about a purely vectorised solution:
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
.
The comparison DF < 0
gives TRUE/FALSE
for every value in the data.frame
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()
then gives us the sum of each row (as TRUE == 1, FALSE == 0
)
rowSums(DF<0)
# [1] 0 0 1 1 0
因此,我们可以使用此向量对data.frame进行子集化.但是,因为我们希望它的值都为正(即rowSums == 0),所以我们取消了过滤器
So we can use this vector to subset our data.frame. But, because we want it where the values are all positive (i.e. rowSums == 0), we negate the filter
DF[!rowSums(DF < 0), ]
这篇关于如何使用循环删除R中所有带有负值的行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!