R - sort() 输出缺少一行 [英] R - sort() output missing a row

查看:43
本文介绍了R - sort() 输出缺少一行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有 AB 如下://编辑//我很困很困惑.这些不是数据框.

I have A and B as follows: //edit// I was sleepy and confused. These are NOT data frames.

> length(A)
[1] 490
> length(B)
[1] 17730

> str(A)
 num [1:490] 0.0113 -0.0106 0.2308 0.0435 0.2814 ...
> str(B)
 num [1:17730] 0.0118 0.0196 0.0344 0.0207 0.0566 ...

但是出于某种原因,当我使用 sort() 时:

But for some reason when I used sort():

> length(sort(A))
[1] 490
> length(sort(B))
[1] 17729        #should be 17730

我不知道如何在这种特殊情况下生成可重现的示例,而且我一直在思考如何解决此问题.我应该检查什么?

I don't know how to produce a reproducible example in this particular case, and I'm stuck on how I should go about troubleshooting this. What should I check?

推荐答案

其他人已经指出 sort() 需要一个向量而不是一个 data.frame,但是向量中是否有任何 NA?sort() 中的默认值是删除 NA:

Others have pointed out that sort() takes a vector and not a data.frame, but are there any NAs in the vector? The default in sort() is to remove NAs:

v <- c(2, 1, NA)
v
#[1]  2  1 NA

length(sort(v))
#[1] 2
length(sort(v, na.last = T))
#[1] 3

如果你想对 data.frame 进行排序,你应该使用 order() 而不是 sort().order()sort() 具有相同的 na.last 参数,但默认值为 TRUE 而不是 <代码>不适用:

If you want to sort a data.frame you should use order() instead of sort(). order() has the same na.last argument as sort() except the default is TRUE instead of NA:

df <- data.frame(vars = c(2, 1, NA))
df_n <- data.frame(df[order(df$vars),])

nrow(df_n)
#[1] 3

这篇关于R - sort() 输出缺少一行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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