如何使用 sapply 向数据框中添加行? [英] How do I add rows to a data frame using sapply?

查看:48
本文介绍了如何使用 sapply 向数据框中添加行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在 sapply 函数调用中向数据框中添加行,但它返回一个矩阵,而我想要一个数据框,其中列中有变量,行中有名称/地址.

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/addresses in the rows.

这是一个说明问题的简单示例.我这样做是为了避免使用for"循环.有人可以教我应该怎么做吗?

This is a trivial example that demonstrates the problem. I'm doing it this way to avoid using a 'for' loop. Can someone please teach me how I should be doing this?

# initialize and empty data frame
absdf <- data.frame(
    name = character(),
    address = character(), 
    city = character(),
    stringsAsFactors=FALSE)

# a numeric vector. 
idvs <- c(123, 465)

print("initial empty data frame:")
print(absdf)

absdf <- sapply(idvs, function(idv) {

    name <- paste("John Doe", idv)
    address <- "123 Main St."
    city <- "Elmhurst"

    absdf <- rbind(absdf, data.frame(
        name = name, 
        address = address,
        city = city,
        stringsAsFactors=FALSE))

})

# print it out - a sanity check
print("absdf final:")
print(absdf)

这是它的输出:

[1] "initial empty data frame:"
[1] name    address city   
<0 rows> (or 0-length row.names)
[1] "absdf final:"
    [,1]           [,2]          
name    "John Doe 123" "John Doe 465"
address "123 Main St." "123 Main St."
city    "Elmhurst"     "Elmhurst"    

最后,为什么它是一个矩阵?

And finally, why is it a matrix?

> class(absdf)
[1] "matrix"

推荐答案

sapply 试图将结果简化为矩阵,但您没有得到预期的输出.

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

来自 apply 中的简化"参数:

From "simplify" parameter in apply:

逻辑或字符串;结果是否应该简化为向量、矩阵或更高如果可能,多维数组?

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

由于 sapplylapply 的包装器以简化输出,请尝试直接使用 lapply 创建数据帧.

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

流行的函数调用 do.call(rbind, <list>) 组合了列表的元素.

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

这篇关于如何使用 sapply 向数据框中添加行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆