Skip to content

Commit 7a79a18

Browse files
try and handle "inner" row names from matrix case
1 parent eb50409 commit 7a79a18

File tree

1 file changed

+15
-6
lines changed

1 file changed

+15
-6
lines changed

R/as.data.table.R

Lines changed: 15 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -138,21 +138,21 @@ as.data.table.list = function(x,
138138
empty_atomic = FALSE
139139

140140
# Handle keep.rownames for vectors (mimicking data.frame behavior)
141-
vector_rownames = NULL
141+
rownames_ = NULL
142142
check_rownames = !isFALSE(keep.rownames)
143143

144144
for (i in seq_len(n)) {
145145
xi = x[[i]]
146146
if (is.null(xi)) next # eachncol already initialized to 0 by integer() above
147-
if (check_rownames && is.null(vector_rownames) && is.atomic(xi)) {
147+
if (check_rownames && is.null(rownames_)) {
148148
if (is.null(dim(xi))) {
149149
if (!is.null(nm <- names(xi)) && any(nzchar(nm))) {
150-
vector_rownames = nm
150+
rn = nm
151151
x[[i]] = unname(xi)
152152
}
153153
} else {
154154
if (!is.null(nm <- rownames(xi)) && any(nzchar(nm))) {
155-
vector_rownames = nm
155+
rownames_ = nm
156156
}
157157
}
158158
}
@@ -222,13 +222,22 @@ as.data.table.list = function(x,
222222
if (check.names) vnames = make.names(vnames, unique=TRUE)
223223

224224
# Add rownames column when vector names were found
225-
if (!is.null(vector_rownames)) {
225+
if (!is.null(rownames_)) {
226226
rn_name = if (is.character(keep.rownames)) keep.rownames[1L] else "rn"
227-
ans = c(list(recycle(vector_rownames, nrow)), ans)
227+
ans = c(list(recycle(rownames_, nrow)), ans)
228228
vnames = c(rn_name, vnames)
229+
} else if (check_rownames) {
230+
# case like data.table(a = 1, data.frame(b = 2, row.names='c')) where expanding the inner DF picks up the row names --
231+
# we want to bump the resulting column to the front of the output
232+
rn_name = if (is.character(keep.rownames)) keep.rownames[1L] else "rn"
233+
if (!is.na(idx <- chmatch(rn_name, names(ans))[1L]) && idx != 1L) {
234+
ans = c(ans[[idx]], ans[-idx])
235+
vnames = c(vnames[idx], vnames[-idx])
236+
}
229237
}
230238
setattr(ans, "names", vnames)
231239
setDT(ans, key=key) # copy ensured above; also, setDT handles naming
240+
if (!is.null(rownames_) && match(rn_name, names(
232241
if (length(origListNames)==length(ans)) setattr(ans, "names", origListNames) # PR 3854 and tests 2058.15-17
233242
ans
234243
}

0 commit comments

Comments
 (0)