简体   繁体   中英

Strange behavior when ordering in R

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM