我正在使用以下内容:
> set.seed(456) > df1 <- data.frame(col1 = runif(10)) > class(df1) [1] "data.frame" > df1 <- df1[order(df1$col1),] > class(df1) [1] "numeric"
但是,如果我添加一个空白列,一切正常:
> set.seed(456) > df1 <- data.frame(col1 = runif(10)) > df1$dummy <- NA > class(df1) [1] "data.frame" > df1 <- df1[order(df1$col1),] > class(df1) [1] "data.frame" > df1 col1 dummy 7 0.08243274 NA 1 0.08955160 NA 2 0.21051232 NA 9 0.23750327 NA 8 0.28552695 NA 6 0.33195997 NA 10 0.38523617 NA 3 0.73295527 NA 5 0.78839789 NA 4 0.85213354 NA
有一个更好的方法吗?
您可以添加drop = FALSE,它将适用于大多数情况. [是drop = TRUE的默认选项df1[order(df1$col1),, drop=FALSE]
在?`[`的帮助页面中,可以在’Usage’中找到默认参数
x[i, j, ... , drop = TRUE]
和drop的描述
drop: For matrices and arrays. If ‘TRUE’ the result is coerced to the lowest possible dimension (see the examples). This only works for extracting elements, not for the replacement. See ‘drop’ for further details.
精彩评论