我怎么知道具有特定条件的行数?在r

发布于 2025-01-25 06:28:38 字数 293 浏览 4 评论 0原文

我有此数据框:

d <- structure(list(a = c(1, 66, 58, 0, 91, 37), b = c(44, 0, 75, 
11, 0, 32), c = c(0, 81, 0, 53, 25, 13)), class = "data.frame", row.names = c(NA, 
-6L))

我需要知道,对于每列,第一个零的位置(行号)。在这种情况下,结果应该

4, 2, 1

如何? THX寻求帮助!

I have this dataframe:

d <- structure(list(a = c(1, 66, 58, 0, 91, 37), b = c(44, 0, 75, 
11, 0, 32), c = c(0, 81, 0, 53, 25, 13)), class = "data.frame", row.names = c(NA, 
-6L))

I need to know, for each column, the position (row number) of the first zero. In this case the result should be

4, 2, 1

How can I do? Thx for help!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

琉璃梦幻 2025-02-01 06:28:38

您可以使用max.col

max.col(t(d) == 0, "first")

如果只有正值,也可以做:

sapply(d, which.min)
# [1] 4 2 1

You can use max.col:

max.col(t(d) == 0, "first")

If you only have positive values, you can also do:

sapply(d, which.min)
# [1] 4 2 1
你的往事 2025-02-01 06:28:38

这是一种方法:

sapply(d, function(x) which(x==0)[1])
# a b c 
# 4 2 1 

Here is one way:

sapply(d, function(x) which(x==0)[1])
# a b c 
# 4 2 1 
那片花海 2025-02-01 06:28:38

另一个可能的解决方案:

apply(d, 2, function(x) which.max(x == 0))

#> a b c 
#> 4 2 1

Another possible solution:

apply(d, 2, function(x) which.max(x == 0))

#> a b c 
#> 4 2 1
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文