File: misc.R

package info (click to toggle)
r-cran-rhandsontable 0.3.6%2Bdfsg1-1
  • links: PTS, VCS
  • area: main
  • in suites: buster
  • size: 2,920 kB
  • sloc: makefile: 18; sh: 10
file content (180 lines) | stat: -rw-r--r-- 5,640 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
# Map R classes to handsontable.js types
get_col_types = function(data) {
  if (is.matrix(data))  {
    types = rep(typeof(data), ncol(data))
  } else if (is.data.frame(data)){
    types = as.character(lapply(data, class))
  } else{
    stop("Unsupported object type: ", class(data), " Can't extract column types.")
  }

  types <- sapply(types, function(type) {
    if (grepl("factor", type)) return("factor")

    switch(type,
           integer="integer",
           double="numeric",
           numeric="numeric",
           character="text",
           logical="checkbox",
           Date="date",
           "text")
  })

  as.character(types)
}

# Convert handsontable to R object
toR = function(data, changes, params, ...) {
  rClass = params$rClass
  colHeaders = unlist(params$rColHeaders)
  rowHeaders = unlist(params$rRowHeaders)
  rColClasses = unlist(params$rColClasses)[colHeaders]

  out = data

  # copy/paste may add rows without firing an afterCreateRow event (still needed?)
  # if (length(out) != length(rowHeaders))
  #   changes$event = "afterCreateRow"

  # remove spare empty rows; autofill fix (not working)
  # if (!is.null(changes$source) && changes$source == "autofill") {
  #   rm_inds = sapply(out, function(x) all(unlist(x) == "NA"))
  #   rm_inds = suppressWarnings(min(which(diff(rm_inds) == -1)))
  #   if (rm_inds != Inf)
  #     out = out[-(length(out) - rm_inds + 1)]
  # }

  # pre-conversion updates; afterCreateCol moved to end of function
  # if (changes$event == "afterCreateRow") {
  #   inds = seq(changes$ind + 1, length.out = changes$ct)
  #   # prevent duplicates
  #   nm = 1
  #   while (nm %in% rowHeaders) {
  #     nm = nm + 1
  #   }
  #   rowHeaders = c(head(rowHeaders, inds - 1), nm,
  #                  tail(rowHeaders, length(rowHeaders) - inds + 1))
  # } else if (changes$event == "afterRemoveRow") {
  #   inds = seq(changes$ind + 1, length.out = changes$ct)
  #   rowHeaders = rowHeaders[-inds]
  if (changes$event == "afterRemoveCol") {
    if (!("matrix" %in% rClass)) {
      inds = seq(changes$ind + 1, 1, length.out = changes$ct)
      rColClasses = rColClasses[-inds]
    }
  }

  # convert
  if ("matrix" %in% rClass) {
    nr = length(out)
    out = unlist(out, recursive = FALSE)
    # replace NULL with NA
    out = unlist(lapply(out, function(x) if (is.null(x)) NA else x))

    # If there is no data create empty matrix
    if (length(out) == 0) {
      out = matrix(nrow = 0, ncol = length(colHeaders))
    } else {
      out = matrix(out, nrow = nr, byrow = TRUE)
    }

    class(out) = params$rColClasses

  } else if ("data.frame" %in% rClass) {
    nr = length(out)

    out = unlist(out, recursive = FALSE)
    # replace NULL with NA
    out = unlist(lapply(out, function(x) if (is.null(x)) NA else x))

    # If there is no data create empty matrix
    if (length(out) == 0) {
      out = matrix(nrow = 0, ncol = length(colHeaders))
    } else {
      out = matrix(out, nrow = nr, byrow = TRUE)
    }

    out = colClasses(as.data.frame(out, stringsAsFactors = FALSE),
                     rColClasses, params$columns, ...)
  } else {
    stop("Conversion not implemented: ", rClass)
  }


  # post-conversion updates
  if (changes$event == "afterCreateRow") {
    # default logical NA in data.frame to FALSE
    if (!("matrix" %in% rClass)) {
      inds_logical = which(rColClasses == "logical")
      for (i in inds_logical)
        out[[i]] = ifelse(is.na(out[[i]]), FALSE, out[[i]])
    }
  }

  if (ncol(out) != length(colHeaders))
    colHeaders = genColHeaders(changes, colHeaders)

  if (nrow(out) != length(rowHeaders) && !is.null(rowHeaders))
    rowHeaders = genRowHeaders(changes, rowHeaders)

  colnames(out) = colHeaders
  rownames(out) = rowHeaders

  if ("data.table" %in% rClass)
    out = as(out, "data.table")

  out
}

# Coerces data.frame columns to the specified classes
# see http://stackoverflow.com/questions/9214819/supply-a-vector-to-classes-of-dataframe
colClasses <- function(d, colClasses, cols, date_fmt = "%m/%d/%Y", ...) {
  colClasses <- rep(colClasses, len=length(d))
  for(i in seq_along(d))
    d[[i]] = switch(
      colClasses[i],
      Date = as.Date(d[[i]], origin='1970-01-01',
                     format = date_fmt),
      POSIXct = as.POSIXct(d[[i]], origin='1970-01-01',
                           format = date_fmt),
      factor = factor(d[[i]],
                      levels = c(unlist(cols[[i]]$source),
                                 unique(d[[i]][!(d[[i]] %in% unlist(cols[[i]]$source))])),
                      ordered = TRUE),
      json = jsonlite::toJSON(d[[i]]),
      suppressWarnings(as(d[[i]], colClasses[i])))
  d
}

genColHeaders <- function(changes, colHeaders) {
  ind_ct = length(which(grepl("V[0-9]{1,}", colHeaders)))

  if (changes$event == "afterRemoveCol") {
    colHeaders[-(seq(changes$ind, length = changes$ct) + 1)]
  } else if (changes$event == "afterCreateCol") {
    # create new column names
    new_cols = paste0("V", changes$ct + ind_ct)
    # insert into vector
    inds = seq(changes$ind + 1, 1, length.out = changes$ct)
    c(colHeaders, new_cols)[order(c(seq_along(colHeaders), inds - 0.5))]
  } else {
    stop("Change no recognized:", changes$event)
  }
}

genRowHeaders <- function(changes, rowHeaders) {
  inds = seq(changes$ind + 1, length.out = changes$ct)

  if (changes$event == "afterCreateRow") {
    # prevent duplicates
    nm = 1
    while (nm %in% rowHeaders) {
      nm = nm + 1
    }
    c(head(rowHeaders, inds - 1), nm,
      tail(rowHeaders, length(rowHeaders) - inds + 1))
  } else if (changes$event == "afterRemoveRow") {
    rowHeaders[-inds]
  }
}