返回不是NA的最后一个数据帧列 [英] Return last data frame column which is not NA

查看:49
本文介绍了返回不是NA的最后一个数据帧列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数据集,其中包含多个标记为1或NA的个案。我试图找出一种方法来返回每种情况下不适用的编号最高的邮票。

I have a dataset consisting of multiple cases that are stamped either 1 OR NA. I'm trying to figure out a way to return the highest numbered stamp that is not NA for each case.

以下是一些示例数据:

PIN <- c("case1", "case2", "case3", "case4", "case5")
STAMP_1 <- c(1, 1, 1, 1, 1)
STAMP_2 <- c(NA, 1, 1, NA, 1)
STAMP_3 <- c(1, NA, 1, 1, NA)
STAMP_4 <- c(NA, NA, 1, 1, NA)
STAMP_5 <- c(1, NA, NA, 1, NA)
data <- data.frame(PIN, STAMP_1, STAMP_2, STAMP_3, STAMP_4, STAMP_5)

想要找出一种返回具有以下列的数据帧的方法: case1, case2, case3, case4, case5和 STAMP_5, STAMP_2, STAMP_4, STAMP_5 , STAMP_2。

I'd like to figure out a way to return a data frame that will have columns: "case1", "case2", "case3", "case4", "case5" AND "STAMP_5", "STAMP_2", "STAMP_4", "STAMP_5", "STAMP_2" in this case.

推荐答案

这里是具有 max.col的方法 is.na 名称 max.col 查找每一行具有最大值的列。在这里,我们将 is.na 的值输入TRUE或FALSE,并使用ties.method = last来获取最终的非NA值。此位置用于索引名称(dat)

Here is a method with max.col, is.na and names. max.col finds the column with the maximum value for each row. Here, we feed it the value of is.na, which is TRUE or FALSE and use ties.method="last" to take the final non-NA value. This position is used to index names(dat).

data.frame(PIN=dat$PIN,
           stamp=names(dat)[-1][max.col(!is.na(dat[-1]), ties.method="last")])
    PIN   stamp
1 case1 STAMP_5
2 case2 STAMP_2
3 case3 STAMP_4
4 case4 STAMP_5
5 case5 STAMP_2

如果您有一整行都包含NA,则 max.col 将返回该行的最终位置(无声失败?)。返回NA而不是该头寸的一种方法是对NA和取幂使用技巧。在这里,我们应用遍历所有行,找到具有任何行且至少具有一个非NA值的任何NA行返回FALSE(或0)。

In the case that you have an entire row with NAs, max.col will return the final position of the row (a silent failure?). One way to return an NA rather than that position is to use a trick with NA and exponentiation. Here, we apply through the rows and find any NA rows with any rows that have at least one non-NA value return FALSE (or 0).

data.frame(PIN=dat$PIN,
           stamp=names(dat)[-1][
                max.col(!is.na(dat[-1]), ties.method="last") * NA^!rowSums(!is.na(dat[-1]))])

我从 applyapply(dat [-1], 1,函数(x)all(is.na(x)))!rowSums(!is.na(dat [-1]))在弗兰克的建议之后。这应该比 apply 快很多。

I switched from applyapply(dat[-1], 1, function(x) all(is.na(x))) to !rowSums(!is.na(dat[-1])) after Frank's suggestion. This should be quite a bit faster than apply.

这篇关于返回不是NA的最后一个数据帧列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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