How do I add rows to a data frame using sapply?

后端 未结 1 1154
北海茫月
北海茫月 2021-01-24 09:02

I\'m trying to add rows to a data frame within an sapply function call, but it\'s returning a matrix, whereas I want a data frame with variables in the columns and names/address

相关标签:
1条回答
  • 2021-01-24 09:42

    sapply is attempting to simplify the result to matrix and you are not getting the output you expect.

    From "simplify" parameter in apply:

    logical or character string; should the result be simplified to a vector, matrix or higher dimensional array if possible?

    Since sapply is a wrapper for lapply to simplify the output, try creating the data frames with lapply directly.

    The popular function call do.call(rbind, <list>) combines the elements of a list.

    absdf <- lapply(idvs, function(idv) {
    
        name <- paste("John Doe", idv)
        address <- "123 Main St."
        city <- "Elmhurst"
    
        data.frame(
            name = name, 
            address = address,
            city = city,
            stringsAsFactors=FALSE)
    
    })
    do.call(rbind, absdf)
    #           name      address     city
    # 1 John Doe 123 123 Main St. Elmhurst
    # 2 John Doe 465 123 Main St. Elmhurst
    
    0 讨论(0)
提交回复
热议问题