Strange behavior when ordering in R

时间:2018-05-28 18:44:13

标签: r sorting

I am a little lost with the following code:

simula <- data.frame(
  a=sample(c("b", "a"), 10, replace=TRUE), 
  b=sample(c("bb", "aa"), 10, replace=TRUE), 
  c=rnorm(10), 
  d=rnorm(10))

order(simula$a, simula$d, decreasing=c(T,F))

The order statement gives an error in which it states that

argument lengths differ

. Which doesn't make a lot of sense to me.

Can anyone explain me why this is giving an error?

1 个答案:

答案 0 :(得分:0)

stringsAsFactors = F should solve the problem:

simula <- data.frame(
  a=sample(c("b", "a"), 10, replace=TRUE), 
  b=sample(c("bb", "aa"), 10, replace=TRUE), 
  c=rnorm(10), d=rnorm(10), stringsAsFactors = FALSE)
order(simula$a, simula$d, decreasing=c(TRUE, FALSE))

Otherwise the variables will be stored as factor, and sample a / b will only have 2 levels, compared to column c / d with 10 elements.