-
Notifications
You must be signed in to change notification settings - Fork 309
/
dataframe.R
1716 lines (1631 loc) · 60 KB
/
dataframe.R
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
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# File src/library/base/R/dataframe.R
# Part of the R package, https://www.R-project.org
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# A copy of the GNU General Public License is available at
# https://www.R-project.org/Licenses/
# Statlib code by John Chambers, Bell Labs, 1994
# Changes Copyright (C) 1998-2024 The R Core Team
## As from R 2.4.0, row.names can be either character or integer.
## row.names() will always return character.
## attr(, "row.names") will return either character or integer.
##
## Do not assume that the internal representation is either, since
## 1L:n is stored as the integer vector c(NA, n) to save space (and
## the C-level code to get/set the attribute makes the appropriate
## translations.
##
## As from 2.5.0 c(NA, n > 0) indicates deliberately assigned row names,
## and c(NA, n < 0) automatic row names.
## We cannot allow long vectors as elements until we can handle
## duplication of row names.
.row_names_info <- function(x, type = 1L)
.Internal(shortRowNames(x, type))
row.names <- function(x) UseMethod("row.names")
row.names.data.frame <- function(x) as.character(attr(x, "row.names"))
row.names.default <- function(x) if(!is.null(dim(x))) rownames(x)# else NULL
.set_row_names <- function(n)
if(n > 0) c(NA_integer_, -n) else integer()
##_H Hack around the fact that other packages fail with a newly improved `row.names<-`:
##_H
##_H `row.names<-` <- function(x, make.names = FALSE, value) UseMethod("row.names<-")
`row.names<-` <- function(x, value) UseMethod("row.names<-")
##_H `row.names<-.data.frame` <-
`.rowNamesDF<-` <- function(x, make.names = FALSE, value)
{
if (!is.data.frame(x)) x <- as.data.frame(x)
n <- .row_names_info(x, 2L)
if(is.null(value)) { # set automatic row.names
attr(x, "row.names") <- .set_row_names(n)
return(x)
}
## do this here, as e.g. POSIXlt changes length when coerced.
if( is.object(value) || !is.integer(value) )
value <- as.character(value)
if(n == 0L) {
## we have to be careful here. This could be a
## 0-row data frame or an invalid one being constructed.
if(!is.null(attr(x, "row.names")) && length(value) > 0L)
stop("invalid 'row.names' length")
}
else if (length(value) != n) {
if(isFALSE(make.names)) stop("invalid 'row.names' length")
else if(is.na(make.names)) { # automatic row.names
attr(x, "row.names") <- .set_row_names(n)
return(x)
}
else if(!isTRUE(make.names)) stop("invalid 'make.names'")
## else make.names = TRUE: amend 'value' to correct ones:
else if((nv <- length(value)) < n)
value <- c(value, rep_len(value[nv], n-nv))
else # length(value) > n
value <- value[seq_len(n)]
}
if (anyDuplicated(value)) {
if(isFALSE(make.names)) {
nonuniq <- sort(unique(value[duplicated(value)]))
## warning + stop ?? FIXME: s/warning/stop/ and drop (2nd) stop ??
warning(ngettext(length(nonuniq),
sprintf("non-unique value when setting 'row.names': %s",
sQuote(nonuniq[1L])),
sprintf("non-unique values when setting 'row.names': %s",
paste(sQuote(nonuniq), collapse = ", "))),
domain = NA, call. = FALSE)
stop("duplicate 'row.names' are not allowed")
}
else if(is.na(make.names)) { # automatic row.names
value <- .set_row_names( # find nrow(.) in case 'n' is not usable:
if(n == 0L && is.null(.row_names_info(x, 0L)) && length(x) > 0L)
length(x[[1L]])
else n)
}
else if(!isTRUE(make.names)) stop("invalid 'make.names'")
else # make.names = TRUE: amend 'value' to correct ones:
value <- make.names(value, unique=TRUE)
## NB: 'value' is now guaranteed to have no NA's ==> can use 'else if' :
}
else if (anyNA(value)) {
if(isFALSE(make.names))
stop("missing values in 'row.names' are not allowed")
if(is.na(make.names)) # automatic row.names
value <- .set_row_names(if(n > 0) n else length(value))
else if(!isTRUE(make.names)) stop("invalid 'make.names'")
else # make.names = TRUE: amend 'value' to correct ones:
value <- make.names(value, unique=TRUE)
}
attr(x, "row.names") <- value
x
}
`row.names<-.data.frame` <- function(x, value) `.rowNamesDF<-`(x, value=value)
##_H `row.names<-.default` <- function(x, ..., value) `rownames<-`(x, value)
`row.names<-.default` <- function(x, value) `rownames<-`(x, value)
is.na.data.frame <- function (x)
{
## need to special-case no columns
y <- if (length(x)) {
do.call(cbind, lapply(x, is.na)) # gives a matrix
} else matrix(FALSE, length(row.names(x)), 0)
if(.row_names_info(x) > 0L) rownames(y) <- row.names(x)
y
}
## Provide for efficiency reasons (PR#17600):
anyNA.data.frame <- function(x, recursive = FALSE)
any(vapply(x, anyNA, NA, USE.NAMES = FALSE))
is.data.frame <- function(x) inherits(x, "data.frame")
## as fast as possible; used also for subsetting
I <- function(x) { class(x) <- unique.default(c("AsIs", oldClass(x))); x }
print.AsIs <- function (x, ...)
{
cl <- oldClass(x)
oldClass(x) <- cl[cl != "AsIs"]
NextMethod("print")
invisible(x)
}
t.data.frame <- function(x)
{
x <- as.matrix(x)
NextMethod("t")
}
dim.data.frame <- function(x) c(.row_names_info(x, 2L), length(x))
dimnames.data.frame <- function(x) list(row.names(x), names(x))
`dimnames<-.data.frame` <- function(x, value)
{
d <- dim(x)
if(!is.list(value) || length(value) != 2L)
stop("invalid 'dimnames' given for data frame")
## do the coercion first, as might change length
value[[1L]] <- as.character(value[[1L]])
value[[2L]] <- as.character(value[[2L]])
if(d[[1L]] != length(value[[1L]]) || d[[2L]] != length(value[[2L]]))
stop("invalid 'dimnames' given for data frame")
row.names(x) <- value[[1L]] # checks validity
names(x) <- value[[2L]]
x
}
as.data.frame <- function(x, row.names = NULL, optional = FALSE, ...)
{
if(is.null(x)) # can't assign class to NULL
return(as.data.frame(list()))
UseMethod("as.data.frame")
}
as.data.frame.default <- function(x, ...) {
if(is.atomic(x))
as.data.frame.vector(x, ...)
else
stop(gettextf("cannot coerce class %s to a data.frame",
sQuote(deparse(class(x))[1L])),
domain = NA)
}
### Here are methods ensuring that the arguments to "data.frame"
### are in a form suitable for combining into a data frame.
as.data.frame.data.frame <- function(x, row.names = NULL, ...)
{
cl <- oldClass(x)
i <- match("data.frame", cl)
if(i > 1L)
class(x) <- cl[ - (1L:(i-1L))]
if(!is.null(row.names)){
nr <- .row_names_info(x, 2L)
if(length(row.names) == nr)
attr(x, "row.names") <- row.names
else
stop(sprintf(ngettext(nr,
"invalid 'row.names', length %d for a data frame with %d row",
"invalid 'row.names', length %d for a data frame with %d rows"),
length(row.names), nr), domain = NA)
}
x
}
## prior to 1.8.0 this coerced names - PR#3280
as.data.frame.list <-
function(x, row.names = NULL, optional = FALSE, ...,
cut.names = FALSE, col.names = names(x), fix.empty.names = TRUE,
new.names = !missing(col.names),
check.names = !optional,
stringsAsFactors = FALSE)
{
## need to protect names in x.
if(cut.names) { ## truncate any of more than 256 (or cut.names) bytes:
maxL <- if(is.logical(cut.names)) 256L else as.integer(cut.names)
if(any(long <- nchar(col.names, "bytes", keepNA = FALSE) > maxL))
col.names[long] <- paste(substr(col.names[long], 1L, maxL - 6L), "...")
else cut.names <- FALSE
}
m <- match(names(formals(data.frame))[-1L],
## c("row.names", "check.rows", ...., "stringsAsFactors"),
col.names, 0L)
if(any.m <- any(m)) col.names[m] <- paste0("..adfl.", col.names[m])
if(new.names || any.m || cut.names) names(x) <- col.names
## data.frame() is picky with its 'row.names':
alis <- c(list(check.names = check.names, fix.empty.names = fix.empty.names,
stringsAsFactors = stringsAsFactors),
if(!missing(row.names)) list(row.names = row.names))
x <- do.call(data.frame, c(x, alis))
if(new.names && !check.names && length(names(x)) == length(col.names) &&
any(naNm <- is.na(col.names)))
names(x)[naNm] <- col.names[naNm]
if(any.m) names(x) <- sub("^\\.\\.adfl\\.", "", names(x))
x
}
as.data.frame.vector <- function(x, row.names = NULL, optional = FALSE, ...,
nm = deparse1(substitute(x)))
{
force(nm)
nrows <- length(x)
if(is.null(row.names)) {
if (nrows == 0L)
row.names <- character()
else if(length(row.names <- names(x)) != nrows || anyDuplicated(row.names))
row.names <- .set_row_names(nrows)
}
else if(!(is.character(row.names) || is.integer(row.names)) || length(row.names) != nrows)
stop(gettextf("'row.names' is not a character or integer vector of length %d", nrows),
domain = NA)
if(!is.null(names(x))) names(x) <- NULL # remove names as from 2.0.0
value <- list(x)
if(!optional) names(value) <- nm
structure(value, row.names = row.names, class = "data.frame")
}
as.data.frame.ts <- function(x, ...)
{
if(is.matrix(x))
as.data.frame.matrix(x, ...)
else
as.data.frame.vector(x, ...)
}
as.data.frame.raw <- as.data.frame.vector
as.data.frame.factor <- as.data.frame.vector
as.data.frame.ordered <- as.data.frame.vector
as.data.frame.integer <- as.data.frame.vector
as.data.frame.logical <- as.data.frame.vector
as.data.frame.numeric <- as.data.frame.vector
as.data.frame.complex <- as.data.frame.vector
## in case someone passes 'nm'
as.data.frame.character <-
function(x, ..., stringsAsFactors = FALSE)
{
nm <- deparse1(substitute(x))
if(stringsAsFactors) x <- factor(x)
if(!"nm" %in% ...names())
as.data.frame.vector(x, ..., nm = nm)
else as.data.frame.vector(x, ...)
}
as.data.frame.matrix <- function(x, row.names = NULL, optional = FALSE, make.names = TRUE, ...,
stringsAsFactors = FALSE)
{
d <- dim(x)
nrows <- d[[1L]]
ncols <- d[[2L]]
ic <- seq_len(ncols)
dn <- dimnames(x)
if(is.null(row.names)) row.names <- dn[[1L]]
collabs <- dn[[2L]]
## These might be NA
if(any(empty <- !nzchar(collabs)))
collabs[empty] <- paste0("V", ic)[empty]
value <- vector("list", ncols)
if(mode(x) == "character" && stringsAsFactors) {
for(i in ic)
value[[i]] <- as.factor(x[,i])
} else {
for(i in ic)
value[[i]] <- as.vector(x[,i])
}
## Explicitly check for NULL in case nrows==0
autoRN <- (is.null(row.names) || length(row.names) != nrows)
if(length(collabs) == ncols)
names(value) <- collabs %||% character()
else if(!optional)
names(value) <- paste0("V", ic)
class(value) <- "data.frame"
if(autoRN)
attr(value, "row.names") <- .set_row_names(nrows)
else
.rowNamesDF(value, make.names=make.names) <- row.names
value
}
as.data.frame.model.matrix <-
function(x, row.names = NULL, optional = FALSE, make.names = TRUE, ...)
{
d <- dim(x)
nrows <- d[[1L]]
dn <- dimnames(x)
row.names <- dn[[1L]]
value <- list(x)
if(!optional) names(value) <- deparse(substitute(x))[[1L]]
# FIXME? better: , nlines=1L or deparse1(.)
class(value) <- "data.frame"
if(!is.null(row.names)) {
row.names <- as.character(row.names)
if(length(row.names) != nrows)
stop(sprintf(ngettext(length(row.names),
"supplied %d row name for %d rows",
"supplied %d row names for %d rows"),
length(row.names), nrows), domain = NA)
.rowNamesDF(value, make.names=make.names) <- row.names
}
else attr(value, "row.names") <- .set_row_names(nrows)
value
}
as.data.frame.array <- function(x, row.names = NULL, optional = FALSE, ...)
{
d <- dim(x)
if(length(d) == 1L) { ## same as as.data.frame.vector, but deparsed here
## c(): better than drop() or as.vector() !
value <- as.data.frame.vector( c(x), row.names, optional, ...)
if(!optional) names(value) <- deparse(substitute(x))[[1L]]
# FIXME? better: , nlines=1L or deparse1(.)
value
} else if (length(d) == 2L) {
## for explicit "array" class; otherwise *.matrix() is dispatched
as.data.frame.matrix(x, row.names, optional, ...)
} else {
dn <- dimnames(x)
dim(x) <- c(d[1L], prod(d[-1L]))
if(!is.null(dn)) {
if(length(dn[[1L]])) rownames(x) <- dn[[1L]]
for(i in 2L:length(d))
if(is.null(dn[[i]])) dn[[i]] <- seq_len(d[i])
colnames(x) <- interaction(expand.grid(dn[-1L]))
}
as.data.frame.matrix(x, row.names, optional, ...)
}
}
## Allow extraction method to have changed the underlying class,
## so re-assign the class based on the result.
`[.AsIs` <- function(x, i, ...) I(NextMethod("["))
## NB: this is called relatively often from data.frame() itself, ...
as.data.frame.AsIs <- function(x, row.names = NULL, optional = FALSE, ...)
{
if(length(dim(x)) == 2L)
as.data.frame.model.matrix(x, row.names, optional)
else { # as.data.frame.vector without removing names
nrows <- length(x)
nm <- deparse1(substitute(x))
if(is.null(row.names)) {
autoRN <- FALSE
if (nrows == 0L)
row.names <- character()
else if(length(row.names <- names(x)) == nrows &&
!anyDuplicated(row.names)) {
}
else {
autoRN <- TRUE
row.names <- .set_row_names(nrows)
}
} else
autoRN <- is.integer(row.names) && length(row.names) == 2L &&
is.na(rn1 <- row.names[[1L]]) && rn1 < 0
value <- list(x)
if(!optional) names(value) <- nm
class(value) <- "data.frame"
## FIXME -- Need to comment the 'row.names(.) <-' case
## if(autoRN)
attr(value, "row.names") <- row.names
## else
## row.names(value) <- row.names
value
}
}
### This is the real "data.frame".
### It does everything by calling the methods presented above.
data.frame <-
function(..., row.names = NULL, check.rows = FALSE, check.names = TRUE,
fix.empty.names = TRUE,
stringsAsFactors = FALSE)
{
data.row.names <-
if(check.rows && is.null(row.names))
function(current, new, i) {
if(is.character(current)) new <- as.character(new)
if(is.character(new)) current <- as.character(current)
if(anyDuplicated(new))
return(current)
if(is.null(current))
return(new)
if(all(current == new) || all(current == ""))
return(new)
stop(gettextf(
"mismatch of row names in arguments of 'data.frame\', item %d", i),
domain = NA)
}
else function(current, new, i) {
current %||%
if(anyDuplicated(new)) {
warning(gettextf(
"some row.names duplicated: %s --> row.names NOT used",
paste(which(duplicated(new)), collapse=",")),
domain = NA)
current
} else new
}
object <- as.list(substitute(list(...)))[-1L]
mirn <- missing(row.names) # record before possibly changing
mrn <- is.null(row.names) # missing or NULL
x <- list(...)
n <- length(x)
if(n < 1L) {
if(!mrn) {
if(is.object(row.names) || !is.integer(row.names))
row.names <- as.character(row.names)
if(anyNA(row.names))
stop("row names contain missing values")
if(anyDuplicated(row.names))
stop(gettextf("duplicate row.names: %s",
paste(unique(row.names[duplicated(row.names)]),
collapse = ", ")),
domain = NA)
} else row.names <- integer()
return(structure(list(), names = character(),
row.names = row.names,
class = "data.frame"))
}
vnames <- names(x)
if(length(vnames) != n)
vnames <- character(n)
no.vn <- !nzchar(vnames)
vlist <- vnames <- as.list(vnames)
nrows <- ncols <- integer(n)
for(i in seq_len(n)) {
## do it this way until all as.data.frame methods have been updated
xi <- if(is.character(x[[i]]) || is.list(x[[i]]))
as.data.frame(x[[i]], optional = TRUE,
stringsAsFactors = stringsAsFactors)
else as.data.frame(x[[i]], optional = TRUE)
nrows[i] <- .row_names_info(xi) # signed for now
ncols[i] <- length(xi)
namesi <- names(xi)
if(ncols[i] > 1L) {
if(length(namesi) == 0L) namesi <- seq_len(ncols[i])
vnames[[i]] <- if(no.vn[i]) namesi
else paste(vnames[[i]], namesi, sep=".")
} else if(length(namesi)) {
vnames[[i]] <- namesi
} else if (fix.empty.names && no.vn[[i]]) {
tmpname <- deparse(object[[i]], nlines = 1L)[1L]
if(startsWith(tmpname, "I(") && endsWith(tmpname, ")")) {
## from 'I(*)', only keep '*':
ntmpn <- nchar(tmpname, "c")
tmpname <- substr(tmpname, 3L, ntmpn - 1L)
}
vnames[[i]] <- tmpname
} ## else vnames[[i]] are not changed
if(mirn && nrows[i] > 0L) {
rowsi <- attr(xi, "row.names")
## Avoid all-blank names
if(any(nzchar(rowsi)))
row.names <- data.row.names(row.names, rowsi, i)
}
nrows[i] <- abs(nrows[i])
vlist[[i]] <- xi
}
nr <- max(nrows)
for(i in seq_len(n)[nrows < nr]) {
xi <- vlist[[i]]
if(nrows[i] > 0L && (nr %% nrows[i] == 0L)) {
## make some attempt to recycle column i
xi <- unclass(xi) # avoid data-frame methods
fixed <- TRUE
for(j in seq_along(xi)) {
xi1 <- xi[[j]]
if(is.vector(xi1) || is.factor(xi1))
xi[[j]] <- rep(xi1, length.out = nr)
else if(is.character(xi1) && inherits(xi1, "AsIs"))
xi[[j]] <- structure(rep(xi1, length.out = nr),
class = class(xi1))
else if(inherits(xi1, "Date") || inherits(xi1, "POSIXct"))
xi[[j]] <- rep(xi1, length.out = nr)
else {
fixed <- FALSE
break
}
}
if (fixed) {
vlist[[i]] <- xi
next
}
}
stop(gettextf("arguments imply differing number of rows: %s",
paste(unique(nrows), collapse = ", ")),
domain = NA)
}
value <- unlist(vlist, recursive=FALSE, use.names=FALSE)
## unlist() drops i-th component if it has 0 columns
vnames <- as.character(unlist(vnames[ncols > 0L]))
if(fix.empty.names && any(noname <- !nzchar(vnames)))
vnames[noname] <- paste0("Var.", seq_along(vnames))[noname]
if(check.names) {
if(fix.empty.names)
vnames <- make.names(vnames, unique=TRUE)
else { ## do not fix ""
nz <- nzchar(vnames)
vnames[nz] <- make.names(vnames[nz], unique=TRUE)
}
}
names(value) <- vnames
if(!mrn) { # non-null row.names arg was supplied
if(length(row.names) == 1L && nr != 1L) { # one of the variables
if(is.character(row.names))
row.names <- match(row.names, vnames, 0L)
if(length(row.names) != 1L ||
row.names < 1L || row.names > length(vnames))
stop("'row.names' should specify one of the variables")
i <- row.names
row.names <- value[[i]]
value <- value[ - i]
} else if ( !is.null(row.names) && length(row.names) != nr )
stop("row names supplied are of the wrong length")
} else if( !is.null(row.names) && length(row.names) != nr ) {
warning("row names were found from a short variable and have been discarded")
row.names <- NULL
}
class(value) <- "data.frame"
if(is.null(row.names))
attr(value, "row.names") <- .set_row_names(nr) #seq_len(nr)
else {
if(is.object(row.names) || !is.integer(row.names))
row.names <- as.character(row.names)
if(anyNA(row.names))
stop("row names contain missing values")
if(anyDuplicated(row.names))
stop(gettextf("duplicate row.names: %s",
paste(unique(row.names[duplicated(row.names)]),
collapse = ", ")),
domain = NA)
row.names(value) <- row.names
}
value
}
### Subsetting and mutation methods
### These are a little less general than S
`[.data.frame` <-
function(x, i, j, drop = if(missing(i)) TRUE else length(cols) == 1)
{
mdrop <- missing(drop)
Narg <- nargs() - !mdrop # number of arg from x,i,j that were specified
has.j <- !missing(j)
if(!all(names(sys.call()) %in% c("", "drop"))
&& !isS4(x)) # at least don't warn for callNextMethod!
warning("named arguments other than 'drop' are discouraged")
if(Narg < 3L) { # list-like indexing or matrix indexing
if(!mdrop) warning("'drop' argument will be ignored")
if(missing(i)) return(x)
if(is.matrix(i))
return(as.matrix(x)[i]) # desperate measures
## zero-column data frames prior to 2.4.0 had no names.
nm <- names(x); if(is.null(nm)) nm <- character()
## if we have NA names, character indexing should always fail
## (for positive index length)
if(!is.character(i) && anyNA(nm)) { # less efficient version
names(nm) <- names(x) <- seq_along(x)
y <- NextMethod("[")
cols <- names(y)
if(anyNA(cols)) stop("undefined columns selected")
cols <- names(y) <- nm[cols]
} else {
y <- NextMethod("[")
cols <- names(y)
if(!is.null(cols) && anyNA(cols))
stop("undefined columns selected")
}
## added in 1.8.0
if(anyDuplicated(cols)) names(y) <- make.unique(cols)
## since we have not touched the rows, copy over the raw row.names
## Claimed at one time at least one fewer copies: PR#15274
attr(y, "row.names") <- .row_names_info(x, 0L)
attr(y, "class") <- oldClass(x)
return(y)
}
if(missing(i)) { # df[, j] or df[ , ]
## not quite the same as the 1/2-arg case, as 'drop' is used.
if(drop && !has.j && length(x) == 1L) return(.subset2(x, 1L))
nm <- names(x); if(is.null(nm)) nm <- character()
if(has.j && !is.character(j) && anyNA(nm)) {
## less efficient version
names(nm) <- names(x) <- seq_along(x)
y <- .subset(x, j)
cols <- names(y)
if(anyNA(cols)) stop("undefined columns selected")
cols <- names(y) <- nm[cols]
} else {
y <- if(has.j) .subset(x, j) else x
cols <- names(y)
if(anyNA(cols)) stop("undefined columns selected")
}
if(drop && length(y) == 1L) return(.subset2(y, 1L))
if(anyDuplicated(cols)) names(y) <- make.unique(cols)
nrow <- .row_names_info(x, 2L)
if(drop && !mdrop && nrow == 1L)
return(structure(y, class = NULL, row.names = NULL))
else {
## Claimed at one time at least one fewer copies: PR#15274
attr(y, "class") <- oldClass(x)
attr(y, "row.names") <- .row_names_info(x, 0L)
return(y)
}
}
### df[i, j] or df[i , ]
## rewritten for R 2.5.0 to avoid duplicating x.
xx <- x
cols <- names(xx) # needed for computation of 'drop' arg
## make a shallow copy
x <- vector("list", length(x))
## attributes(x) <- attributes(xx) expands row names
x <- .Internal(copyDFattr(xx, x))
oldClass(x) <- attr(x, "row.names") <- NULL
if(has.j) { # df[i, j]
nm <- names(x); if(is.null(nm)) nm <- character()
if(!is.character(j) && anyNA(nm))
names(nm) <- names(x) <- seq_along(x)
x <- x[j]
cols <- names(x) # needed for 'drop'
if(drop && length(x) == 1L) {
## for consistency with [, <length-1>]
if(is.character(i)) {
rows <- attr(xx, "row.names")
i <- pmatch(i, rows, duplicates.ok = TRUE)
}
## need to figure which col was selected:
## cannot use .subset2 directly as that may
## use recursive selection for a logical index.
xj <- .subset2(.subset(xx, j), 1L)
return(if(length(dim(xj)) != 2L) xj[i] else xj[i, , drop = FALSE])
}
if(anyNA(cols)) stop("undefined columns selected")
## fix up names if we altered them.
if(!is.null(names(nm))) cols <- names(x) <- nm[cols]
## sxx <- match(cols, names(xx)) fails with duplicate names
nxx <- structure(seq_along(xx), names=names(xx))
sxx <- match(nxx[j], seq_along(xx))
} else sxx <- seq_along(x)
rows <- NULL # placeholder: only create row names when needed
# as this can be expensive.
if(is.character(i)) {
rows <- attr(xx, "row.names")
i <- pmatch(i, rows, duplicates.ok = TRUE)
}
for(j in seq_along(x)) {
xj <- xx[[ sxx[j] ]]
## had drop = drop prior to 1.8.0
x[[j]] <- if(length(dim(xj)) != 2L) xj[i] else xj[i, , drop = FALSE]
}
if(drop) {
n <- length(x)
if(n == 1L) return(x[[1L]]) # drops attributes
if(n > 1L) {
xj <- x[[1L]]
nrow <- if(length(dim(xj)) == 2L) dim(xj)[1L] else length(xj)
## for consistency with S: don't drop (to a list)
## if only one row, unless explicitly asked for
drop <- !mdrop && nrow == 1L
} else drop <- FALSE ## for n == 0
}
if(!drop) { # not else as previous section might reset drop
## row names might have NAs.
if(is.null(rows)) rows <- attr(xx, "row.names")
rows <- rows[i]
if((ina <- anyNA(rows)) | (dup <- anyDuplicated(rows))) {
## both will coerce integer 'rows' to character:
if (!dup && is.character(rows)) dup <- "NA" %in% rows
if(ina)
rows[is.na(rows)] <- "NA"
if(dup)
rows <- make.unique(as.character(rows))
}
## new in 1.8.0 -- might have duplicate columns
if(has.j && anyDuplicated(nm <- names(x)))
names(x) <- make.unique(nm)
if(is.null(rows)) rows <- attr(xx, "row.names")[i]
attr(x, "row.names") <- rows
oldClass(x) <- oldClass(xx)
}
x
}
`[[.data.frame` <- function(x, ..., exact=TRUE)
{
## use in-line functions to refer to the 1st and 2nd ... arguments
## explicitly. Also will check for wrong number or empty args
na <- nargs() - !missing(exact)
if(!all(names(sys.call()) %in% c("", "exact")))
warning("named arguments other than 'exact' are discouraged")
if(na < 3L)
(function(x, i, exact)
if(is.matrix(i)) as.matrix(x)[[i]]
else .subset2(x, i, exact=exact))(x, ..., exact=exact)
else {
col <- .subset2(x, ..2, exact=exact)
i <- if(is.character(..1))
pmatch(..1, row.names(x), duplicates.ok = TRUE)
else ..1
## we do want to dispatch on methods for a column.
## .subset2(col, i, exact=exact)
col[[i, exact = exact]]
}
}
`[<-.data.frame` <- function(x, i, j, value)
{
if(!all(names(sys.call()) %in% c("", "value")))
warning("named arguments are discouraged")
nA <- nargs() # 'value' is never missing, so 3 or 4.
if(nA == 4L) { ## df[,] or df[i,] or df[, j] or df[i,j]
has.i <- !missing(i)
has.j <- !missing(j)
}
else if(nA == 3L) {
## this collects both df[] and df[ind]
if (is.atomic(value) && !is.null(names(value)))
names(value) <- NULL
if(missing(i) && missing(j)) { # case df[]
i <- j <- NULL
has.i <- has.j <- FALSE
## added in 1.8.0
if(is.null(value)) return(x[logical()])
} else { # case df[ind]
## really ambiguous, but follow common use as if list
## except for two column numeric matrix or full-sized logical matrix
if(is.numeric(i) && is.matrix(i) && ncol(i) == 2) {
# Rewrite i as a logical index
index <- rep.int(FALSE, prod(dim(x)))
dim(index) <- dim(x)
tryCatch(index[i] <- TRUE,
error = function(e) stop(conditionMessage(e), call.=FALSE))
# Put values in the right order
o <- order(i[,2], i[,1])
N <- length(value)
if (length(o) %% N != 0L)
warning("number of items to replace is not a multiple of replacement length")
if (N < length(o))
value <- rep(value, length.out=length(o))
value <- value[o]
i <- index
}
if(is.logical(i) && is.matrix(i) && all(dim(i) == dim(x))) {
nreplace <- sum(i, na.rm=TRUE)
if(!nreplace) return(x) # nothing to replace
## allow replication of length(value) > 1 in 1.8.0
N <- length(value)
if(N > 1L && N < nreplace && (nreplace %% N) == 0L)
value <- rep(value, length.out = nreplace)
if(N > 1L && (length(value) != nreplace))
stop("'value' is the wrong length")
n <- 0L
nv <- nrow(x)
for(v in seq_len(dim(i)[2L])) {
thisvar <- i[, v, drop = TRUE]
nv <- sum(thisvar, na.rm = TRUE)
if(nv) {
if(is.matrix(x[[v]]))
x[[v]][thisvar, ] <- if(N > 1L) value[n+seq_len(nv)] else value
else
x[[v]][thisvar] <- if(N > 1L) value[n+seq_len(nv)] else value
}
n <- n+nv
}
return(x)
} # end of logical matrix
if(is.matrix(i))
stop("unsupported matrix index in replacement")
j <- i
i <- NULL
has.i <- FALSE
has.j <- TRUE
}
}
else # nargs() <= 2
stop("need 0, 1, or 2 subscripts")
if ((has.j && !length(j)) || # "no", i.e. empty columns specified
(has.i && !length(i) && !has.j))# empty rows and no col. specified
return(x)
cl <- oldClass(x)
## delete class: S3 idiom to avoid any special methods for [[, etc
class(x) <- NULL
new.cols <- NULL
nvars <- length(x)
nrows <- .row_names_info(x, 2L)
if(has.i && length(i)) { # df[i, ] or df[i, j]
rows <- NULL # indicator that it is not yet set
if(anyNA(i))
stop("missing values are not allowed in subscripted assignments of data frames")
if(char.i <- is.character(i)) {
rows <- attr(x, "row.names")
ii <- match(i, rows)
nextra <- sum(new.rows <- is.na(ii))
if(nextra > 0L) {
ii[new.rows] <- seq.int(from = nrows + 1L, length.out = nextra)
new.rows <- i[new.rows]
}
i <- ii
}
if(!is.logical(i) &&
(char.i && nextra || all(i >= 0L) && (nn <- max(i)) > nrows)) {
## expand
if(is.null(rows)) rows <- attr(x, "row.names")
if(!char.i) {
nrr <- (nrows + 1L):nn
if(inherits(value, "data.frame") &&
(dim(value)[1L]) >= length(nrr)) {
new.rows <- attr(value, "row.names")[seq_along(nrr)]
repl <- duplicated(new.rows) | match(new.rows, rows, 0L)
if(any(repl)) new.rows[repl] <- nrr[repl]
}
else new.rows <- nrr
}
x <- xpdrows.data.frame(x, rows, new.rows)
rows <- attr(x, "row.names")
nrows <- length(rows)
}
iseq <- seq_len(nrows)[i]
if(anyNA(iseq)) stop("non-existent rows not allowed")
}
else iseq <- NULL
if(has.j) {
if(anyNA(j))
stop("missing values are not allowed in subscripted assignments of data frames")
if(is.character(j)) {
if("" %in% j) stop("column name \"\" cannot match any column")
jseq <- match(j, names(x))
if(anyNA(jseq)) {
n <- is.na(jseq)
jseq[n] <- nvars + seq_len(sum(n))
new.cols <- j[n]
}
}
else if(is.logical(j) || min(j) < 0L)
jseq <- seq_along(x)[j]
else {
jseq <- j
if(max(jseq) > nvars) {
new.cols <- paste0("V",
seq.int(from = nvars + 1L, to = max(jseq)))
if(length(new.cols) != sum(jseq > nvars))
stop("new columns would leave holes after existing columns")
## try to use the names of a list `value'
if(is.list(value) && !is.null(vnm <- names(value))) {
p <- length(jseq)
if(length(vnm) < p) vnm <- rep_len(vnm, p)
new.cols <- vnm[jseq > nvars]
}
}
}
}
else jseq <- seq_along(x)
## empty rows and not (a *new* column as in d[FALSE, "new"] <- val ) :
if(has.i && !length(iseq) && all(1L <= jseq & jseq <= nvars))
return(`class<-`(x, cl))
## addition in 1.8.0
if(anyDuplicated(jseq))
stop("duplicate subscripts for columns")
n <- length(iseq)
if(n == 0L) n <- nrows
p <- length(jseq)
if (is.null(value)) {
value <- list(NULL)
}
m <- length(value)
if(!is.list(value)) {
if(p == 1L) {
N <- NROW(value)
if(N > n)
stop(sprintf(ngettext(N,
"replacement has %d row, data has %d",
"replacement has %d rows, data has %d"),
N, n), domain = NA)
if(N < n && N > 0L)
if(n %% N == 0L && length(dim(value)) <= 1L)
value <- rep(value, length.out = n)
else
stop(sprintf(ngettext(N,
"replacement has %d row, data has %d",
"replacement has %d rows, data has %d"),
N, nrows), domain = NA)
if (!is.null(names(value))) names(value) <- NULL
value <- list(value)
} else {
if(m < n*p && (m == 0L || (n*p) %% m))
stop(sprintf(ngettext(m,
"replacement has %d item, need %d",
"replacement has %d items, need %d"),
m, n*p), domain = NA)
value <- matrix(value, n, p) ## will recycle
## <FIXME split.matrix>
value <- split(c(value), col(value))
}
dimv <- c(n, p)
} else { # a list
## careful, as.data.frame turns things into factors.
## value <- as.data.frame(value)
value <- unclass(value) # to avoid data frame indexing
lens <- vapply(value, NROW, 1L)
for(k in seq_along(lens)) {
N <- lens[k]
if(n != N && length(dim(value[[k]])) == 2L)
stop(sprintf(ngettext(N,
"replacement element %d is a matrix/data frame of %d row, need %d",
"replacement element %d is a matrix/data frame of %d rows, need %d"),
k, N, n),
domain = NA)
if(N > 0L && N < n && n %% N)
stop(sprintf(ngettext(N,
"replacement element %d has %d row, need %d",
"replacement element %d has %d rows, need %d"),
k, N, n), domain = NA)
## these fixing-ups will not work for matrices
if(N > 0L && N < n) value[[k]] <- rep(value[[k]], length.out = n)
if(N > n) {
warning(sprintf(ngettext(N,
"replacement element %d has %d row to replace %d rows",
"replacement element %d has %d rows to replace %d rows"),
k, N, n), domain = NA)
value[[k]] <- value[[k]][seq_len(n)]
}
}
dimv <- c(n, length(value))
}
nrowv <- dimv[1L]
if(nrowv < n && nrowv > 0L) {
if(n %% nrowv == 0L)
value <- value[rep_len(seq_len(nrowv), n),,drop = FALSE]
else
stop(sprintf(ngettext(nrowv,
"%d row in value to replace %d rows",