JamAndJammies JamAndJammies - 2 months ago 6
R Question

DataTable sorts number by reading left to right in a column

When using the datatable, the numbers are sorted reading from left to right, instead of right to left. I have it converted to numeric too. Why does it do this? See * numbers
It does the same with all columns.

Here's an example: 950 should be the first one, not 96.67

Items RN.2015 RN.2016 Change.RN
London 30 59 **96.67**
Tokyo 2 21 **950**
Paris 2 21 950
Seoul 2 21 950
New York20 39 95
Orlando 18 35 94.44
Nice 3 31 **933.3**


code in reactive:

library(dplyr)
fileInfo$RN <- as.numeric(as.character(fileInfo$RN))
perChange<-fileInfo %>%
group_by_(input$selCol) %>%
summarise(
RN.2015 = sum(RN[Year=="2015"]),
RN.2016 = sum(RN[Year=="2016"])
)%>%
mutate(
Change.RN = delt(RN.2015,RN.2016)
)


function

delt <- function(x,y) {ifelse(is.finite((y-x)/x*100),paste0(formatC((y-x)/x*100),"%"),"")}


data:

Data <- data.frame(
Items = c("London","Tokyo","Paris","Seoul","New York","Orlando","Nice"),
RN.2015 = c(30,2,2,2,20,18,3),
RN.2016 = c(59,21,21,21,39,35,31)
)

Answer

In your function delt, paste0 is returning a character vector, so that column is probably getting converted to character.

The sort behavior above is consistent with the way a numeric value could get sorted if it was incorrectly stored as a character vector. 96.6 > 955 > 94, etc.

Use str(data) and ensure that column Change.RN is actually a numeric. If not, use as.numeric to convert.