在满足条件并删除上面的所有内容的数据框中找到第一行? 我在R中有一个数据框: COL1 COL2 COL3 COL4 COL5 1 1 a x 10.5 false 2 2 b y 20.3 true 3 3 C Z 30.7错误 4 4苹果派:W 40.1是真的 5 5 E V 50.9 AP ...

问题描述 投票:0回答:1

我想找到“苹果”一词的第一行,并在此上方删除所有行。

我知道如何通过多个步骤进行操作:
first_apple_row <- min(which(apply(sample_df, 1, function(row) any(grepl("apple", row)))))
result_df <- sample_df[first_apple_row:nrow(sample_df),]

  col1       col2 col3 col4  col5
4    4 apple pie:    w 40.1  TRUE
5    5          e    v 50.9 apple

r中的功能可以更直接地完成?

虽然不是最快,但很简单。我们可以在列上迭代:

i = min(as.numeric(sapply(sample_df, \(i) grep('apple', i))), na.rm=TRUE)
sample_df[-seq(i-1), ]

col1 col2 col3 col4 col5 4 4 apple pie: w 40.1 TRUE 5 5 e v 50.9 apple

r
1个回答
0
投票

最新问题
© www.soinside.com 2019 - 2025. All rights reserved.