Bug 16663 - get_all_vars produces wrong column names
Summary: get_all_vars produces wrong column names
Status: UNCONFIRMED
Alias: None
Product: R
Classification: Unclassified
Component: Low-level (show other bugs)
Version: R 3.2.3
Hardware: All Linux
: P5 normal
Assignee: R-core
URL:
Depends on:
Blocks:
 
Reported: 2016-01-11 12:01 UTC by Werner A. Stahel
Modified: 2016-01-11 12:01 UTC (History)
0 users

See Also:


Attachments

Note You need to log in before you can comment on or make changes to this bug.
Description Werner A. Stahel 2016-01-11 12:01:40 UTC
get_all_vars  produces wrong column names when a variable is a matrix

y <- cbind(a=1:3,4:6)
x <- 7:9
get_all_vars(y~x)

 y x NA
1 1 4  7
2 2 5  8
3 3 6  9

should be

 y.a y.V2 x
1   1    4 7
2   2    5 8
3   3    6 9

which is produced by the following fixed version
(changed lines end by ## !!!

get_all_vars <- 
function (formula, data = NULL, ...) 
{
    if (missing(formula)) {
        if (!missing(data) && inherits(data, "data.frame") && 
            length(attr(data, "terms"))) 
            return(data)
        formula <- as.formula(data)
    }
    else if (missing(data) && inherits(formula, "data.frame")) {
        if (length(attr(formula, "terms"))) 
            return(formula)
        data <- formula
        formula <- as.formula(data)
    }
    formula <- as.formula(formula)
    if (missing(data)) 
        data <- environment(formula)
    else if (!is.data.frame(data) && !is.environment(data) && 
        !is.null(attr(data, "class"))) 
        data <- as.data.frame(data)
    else if (is.array(data)) 
        stop("'data' must be a data.frame, not a matrix or an array")
    if (!inherits(formula, "terms")) 
        formula <- terms(formula, data = data)
    env <- environment(formula)
    rownames <- .row_names_info(data, 0L)
    varnames <- all.vars(formula)
    inp <- parse(text = paste("list(", paste(varnames, collapse = ","), 
        ")"), keep.source = FALSE)
    variables <- setNames(eval(inp, data, env), varnames) ## !!!
    if (is.null(rownames) && (resp <- attr(formula, "response")) > 
        0) {
        lhs <- variables[[resp]]
        rownames <- if (is.matrix(lhs)) 
            rownames(lhs)
        else names(lhs)
    }
    extras <- substitute(list(...))
    extranames <- names(extras[-1L])
    extras <- setNames(eval(extras, data, env),extranames) ## !!!
    x <- data.frame(c(variables, extras)) ## !!!
    if (!is.null(rownames)) 
        attr(x, "row.names") <- rownames
    x
}