@@ -42,37 +42,49 @@ unite.data.frame <- function(data, col, ..., sep = "_", remove = TRUE, na.rm = F
42
42
check_bool(remove )
43
43
check_bool(na.rm )
44
44
45
+ col <- as_string(ensym(col ))
46
+ col <- enc2utf8(col )
47
+
45
48
if (dots_n(... ) == 0 ) {
46
- from_vars <- set_names(seq_along(data ), names(data ))
49
+ selection <- set_names(seq_along(data ), names(data ))
47
50
} else {
48
- from_vars <- tidyselect :: eval_select(expr(c(... )), data , allow_rename = FALSE )
51
+ selection <- tidyselect :: eval_select(expr(c(... )), data , allow_rename = FALSE )
49
52
}
50
53
54
+ empty_selection <- length(selection ) == 0L
55
+
51
56
out <- data
52
57
if (remove ) {
53
- out <- out [setdiff(names(out ), names(from_vars ))]
58
+ out <- out [setdiff(names(out ), names(selection ))]
54
59
}
55
60
56
- if (identical(na.rm , TRUE )) {
57
- cols <- unname(map(data [from_vars ], as.character ))
61
+ if (empty_selection ) {
62
+ # Use initial value implied by the reduction algorithm (#1570)
63
+ united <- vec_rep(" " , times = vec_size(data ))
64
+ } else if (identical(na.rm , TRUE )) {
65
+ cols <- unname(map(data [selection ], as.character ))
58
66
rows <- transpose(cols )
59
-
60
67
united <- map_chr(rows , function (x ) paste0(x [! is.na(x )], collapse = sep ))
61
68
} else {
62
- cols <- unname(as.list(data [from_vars ]))
69
+ cols <- unname(as.list(data [selection ]))
63
70
united <- exec(paste , !!! cols , sep = sep )
64
71
}
65
72
66
- var <- as_string(ensym(col ))
67
- var <- enc2utf8(var )
68
-
69
73
united <- list (united )
70
- names(united ) <- var
74
+ names(united ) <- col
71
75
72
- first_pos <- which(names(data ) %in% names(from_vars ))[1 ]
73
- after <- first_pos - 1L
76
+ if (empty_selection ) {
77
+ after <- length(data )
78
+ } else {
79
+ loc_first_selection <- which(names(data ) %in% names(selection ))[[1L ]]
80
+ after <- loc_first_selection - 1L
81
+ }
74
82
75
83
out <- df_append(out , united , after = after )
76
84
77
- reconstruct_tibble(data , out , if (remove ) names(from_vars ))
85
+ reconstruct_tibble(
86
+ input = data ,
87
+ output = out ,
88
+ ungrouped_vars = if (remove ) names(selection )
89
+ )
78
90
}
0 commit comments