如何获取最后一个非NA列的值 [英] How to get value of last non-NA column
问题描述
有点难以解释,但是我有一个数据框,其值看起来像一个阶梯-对于每个日期,都有不同的列,其中某些日期具有NA.我想创建一个新列,其中包含最后一个非NA列的值.
A bit difficult to explain, but I have a dataframe with values that look like a staircase - for every date, there are different columns that have NA for some dates. I want to create a new column that has the last non-NA column value in it.
希望这个例子更有意义:
Hopefuly it makes more sense with this example:
示例数据框:
test <- data.frame("date" = c(as.Date("2020-01-01"), as.Date("2020-01-02"), as.Date("2020-01-03")),
"a" = c(4, 3, 4),
"b" = c(NA, 2, 1),
"c" = c(NA, NA, 5))
所需的输出:
date............val
2020-01-01...... 4
2020-01-02...... 2
2020-01-03...... 5
我也不想做类似日期的行号和那列号+ 1的事情,但是如果那是唯一的方法,那就那样.谢谢!
I'd also prefer not to do something like take the row number of the date and take that column number + 1, but if that's the only way to do it, that's that. Thanks!
推荐答案
您可以将 max.col
与 ties.method
设置为"last"一起使用;
以获得每行中的最后一个非NA值.
You can use max.col
with ties.method
set as "last"
to get last non-NA value in each row.
test$val <- test[cbind(1:nrow(test), max.col(!is.na(test), ties.method = 'last'))]
test
# date a b c val
#1 2020-01-01 4 NA NA 4
#2 2020-01-02 3 2 NA 2
#3 2020-01-03 4 1 5 5
这篇关于如何获取最后一个非NA列的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!