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

自古美人都是妖i 提交于 2019-12-02 09:52:47

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
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!