[英]dplyr: Need help returning column index of first non-NA value in every row
I've recently started trying to do all of my code in the tidyverse. 我最近开始尝试在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. 这是一个我在tidyverse中无法完成的简单任务:我需要一个数据帧中的列,它返回左边第一个非na值的位置索引。 Does anyone know how to achieve this in dplyr using mutate? 有谁知道如何使用mutate在dplyr中实现这一目标?
Here is the desired output. 这是所需的输出。
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)
)
An easier and efficient base R
option would be max.col
after replacing the NA
elements to 0 将NA
元素替换为0后,更简单有效的base R
选项是max.col
max.col(replace(df2[1:4], is.na(df2[1:4]), 0), 'first')
Or even 甚至
df2$FirstNonNaPosition <- max.col(!is.na(df2[1:4]), "first")
df2$FirstNonNaPosition
#[1] 1 2 3 3 4 4 4 4 4
With tidyverse
, a possible option is pmap
使用tidyverse
,可能的选项是pmap
df2 %>%
mutate(FirstNonNaPosition = pmap_int(.[-5], ~
which.max(!is.na(c(...)))))
Or wrap the max.col
或者包装max.col
df2 %>%
mutate(FirstNonNaPosition = max.col(!is.na(.[-5]), 'first'))
df2 <- structure(list(X1 = c(100, NA, NA, NA, NA, NA, NA, NA, NA), X2 = c(NA,
10, NA, NA, NA, NA, NA, NA, NA), X3 = c(NA, NA, 1000, 1000, NA,
NA, NA, NA, NA), X4 = c(NA, NA, NA, NA, 25, 50, 10, 40, 50),
FirstNonNaPosition = c(1, 2, 3, 3, 4, 4, 4, 4, 4)),
class = "data.frame", row.names = c(NA,
-9L))
Also a base R
possibility: 也是base R
可能性:
apply(df, 1, which.max)
[1] 1 2 3 3 4 4 4 4 4
The same with dplyr
: 与dplyr
相同:
df %>%
mutate(FirstNonNaPosition = apply(., 1, which.max))
A modification for a scenario mentioned by @Andrew: 对@Andrew提到的场景的修改:
apply(df, 1, function(x) which.max(!is.na(x)))
The same with dplyr
: 与dplyr
相同:
df %>%
mutate(FirstNonNaPosition = apply(., 1, function(x) which.max(!is.na(x))))
You could use apply
as well: 您也可以使用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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.