选择行中的最后一行 [英] Select last value in a row, by row
本文介绍了选择行中的最后一行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
以下是一个示例数据框:
df< read.table(tc< - textConnection(
var1 var2 var3 var4
1 2 NA NA
4 4 NA 6
2 NA 3 NA
4 4 4 4
1 NA NA NA),header = TRUE);关闭(tc)
因此,我想要的值向量为 c 2,6,3,4,1)
。
我只是无法弄清楚如何让R识别最后一个值。
任何帮助都不胜感激!
解决方案
东西:
- 使用
is.na标识
NA
- 在
尾部
中查找向量中的最后一个值 - 使用
应用
将此函数应用于data.frame
代码:
lastValue< - function(x)tail (x [!is.na(x)],1)
apply(df,1,lastValue)
[1] 2 6 3 4 1
I have a data frame where each row is a vector of values of varying lengths. I would like to create a vector of the last true value in each row.
Here is an example data frame:
df <- read.table(tc <- textConnection("
var1 var2 var3 var4
1 2 NA NA
4 4 NA 6
2 NA 3 NA
4 4 4 4
1 NA NA NA"), header = TRUE); close(tc)
The vector of values I want would therefore be c(2,6,3,4,1)
.
I just can't figure out how to get R to identify the last value.
Any help is appreciated!
解决方案
Do this by combining three things:
- Identify
NA
values withis.na
- Find the last value in a vector with
tail
- Use
apply
to apply this function to each row in thedata.frame
The code:
lastValue <- function(x) tail(x[!is.na(x)], 1)
apply(df, 1, lastValue)
[1] 2 6 3 4 1
这篇关于选择行中的最后一行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文