删除 r 中低于一行的行
Delete rows below one in r
我想删除特定行下面的行。假设我有两个数据框,我总是提取第一个值:
df1[1,1]
[1,1]= 153548
基于将在另一个数据框的第一列某处找到的值,我想保留所有行高于该值并删除低于该值的所有内容。
如果您的意思是“将所有行保留在相同值所在位置的上方”,那么也许您可以尝试
df2[cumsum(df2[,1]==df1[1,1])==0,]
定义一个逻辑条件来查找具有截止值的行,然后在逻辑向量上使用cumsum
。对于高于第一次出现的截止值的行,结果将为零。
# Example data
df <- data.frame(x = 1:5, y = letters[1:5], stringsAsFactors = FALSE)
print(df)
x y
1 1 a
2 2 b
3 3 c
4 4 d
5 5 e
x == 3 以上行的简短解决方案
df[cumsum(df$x == 3) == 0, ]
结果
x y
1 1 a
2 2 b
同一事物的更详细说明:
# Identify the cutoff row
cutoff_value <- 3
df$cutoff_row <- df$x == cutoff_value
# identify rows above and below
df$cumsum <- cumsum(df$cutoff_row)
df$rows_above <- cumsum(df$cutoff_row) == 0
print(df)
x y cutoff_row cumsum rows_above
1 1 a FALSE 0 TRUE
2 2 b FALSE 0 TRUE
3 3 c TRUE 1 FALSE
4 4 d FALSE 1 FALSE
5 5 e FALSE 1 FALSE
子集
df[df$rows_above == TRUE, c("x", "y")]
同样的结果
x y
1 1 a
2 2 b
我想删除特定行下面的行。假设我有两个数据框,我总是提取第一个值:
df1[1,1]
[1,1]= 153548
基于将在另一个数据框的第一列某处找到的值,我想保留所有行高于该值并删除低于该值的所有内容。
如果您的意思是“将所有行保留在相同值所在位置的上方”,那么也许您可以尝试
df2[cumsum(df2[,1]==df1[1,1])==0,]
定义一个逻辑条件来查找具有截止值的行,然后在逻辑向量上使用cumsum
。对于高于第一次出现的截止值的行,结果将为零。
# Example data
df <- data.frame(x = 1:5, y = letters[1:5], stringsAsFactors = FALSE)
print(df)
x y
1 1 a
2 2 b
3 3 c
4 4 d
5 5 e
x == 3 以上行的简短解决方案
df[cumsum(df$x == 3) == 0, ]
结果
x y
1 1 a
2 2 b
同一事物的更详细说明:
# Identify the cutoff row
cutoff_value <- 3
df$cutoff_row <- df$x == cutoff_value
# identify rows above and below
df$cumsum <- cumsum(df$cutoff_row)
df$rows_above <- cumsum(df$cutoff_row) == 0
print(df)
x y cutoff_row cumsum rows_above
1 1 a FALSE 0 TRUE
2 2 b FALSE 0 TRUE
3 3 c TRUE 1 FALSE
4 4 d FALSE 1 FALSE
5 5 e FALSE 1 FALSE
子集
df[df$rows_above == TRUE, c("x", "y")]
同样的结果
x y
1 1 a
2 2 b