dplyr:需要帮助返回每行中第一个非NA值的列索引 [英] dplyr: Need help returning column index of first non-NA value in every row

查看:23
本文介绍了dplyr:需要帮助返回每行中第一个非NA值的列索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近开始尝试在tidyverse中完成所有代码.这有时使我陷入困境.这是我在tidyverse中无法完成的简单任务:我需要一个数据框中的列,该列从左侧返回第一个non-na值的位置索引.有谁知道如何使用mutate在dplyr中实现这一目标?

I've recently started trying to do all of my code in the tidyverse. This has sometimes lead me to difficulties. Here is a simple task that I haven't been able to complete in the tidyverse: I need a column in a dataframe that returns the position index of the first non-na value from the left. Does anyone know how to achieve this in dplyr using mutate?

这是所需的输出.

data.frame(                           
"X1"=c(100,rep(NA,8)),
"X2"=c(NA,10,rep(NA,7)),
"X3"=c(NA,NA,1000,1000,rep(NA,5)),
"X4"=c(rep(NA,4),25,50,10,40,50),
"FirstNonNaPosition"=c(1,2,3,3,4,4,4,4,4)
)

推荐答案

您也可以使用 apply :

data.frame(                           
"X1"=c(100,rep(NA,8)),
"X2"=c(NA,10,rep(NA,7)),
"X3"=c(NA,NA,1000,1000,rep(NA,5)),
"X4"=c(rep(NA,4),25,50,10,40,50),
"FirstNonNaPosition"=c(1,2,3,3,4,4,4,4,4)
) %>%
  mutate(First_Non_NA_Pos = apply(., 1, function(x) which(!is.na(x))[1]))

   X1 X2   X3 X4 FirstNonNaPosition First_Non_NA_Pos
1 100 NA   NA NA                  1                1
2  NA 10   NA NA                  2                2
3  NA NA 1000 NA                  3                3
4  NA NA 1000 NA                  3                3
5  NA NA   NA 25                  4                4
6  NA NA   NA 50                  4                4
7  NA NA   NA 10                  4                4
8  NA NA   NA 40                  4                4
9  NA NA   NA 50                  4                4

这篇关于dplyr:需要帮助返回每行中第一个非NA值的列索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆