【问题标题】:R - Apply a 3 arguments function to each line of a 3 columns matrix, using as arguments each value of the 3 columnsR - 将 3 参数函数应用于 3 列矩阵的每一行,使用 3 列的每个值作为参数
【发布时间】:2020-09-19 10:21:25
【问题描述】:

我有一个 getSentiment 函数(来自“edgar”R 包),它为我提供了一个包含一组度量的数据框,其工作方式如下:

getSentiment(cik.no = "cik_number", form.type = "form_type", filing_year = year)

该函数不适用于向量,因此我无法使用 C("cik_number1", "cik_number2") 检查多个 cik 号码,对于表格类型和归档年份也是如此。 在我这边,我有一个包含 700 多家公司的矩阵,有 3 列,一列用于 cik 编号,一列用于表格类型,最后一列用于申请年份。 我想要的是将 getSentiment 函数应用于矩阵的每一行/观察,将 3 列中存在的每一行的对应值作为参数。 然后,为了完成它,我想将我为每家公司获得的所有数据框按执行顺序重新绑定到 1 个大矩阵中。

也许解决方案很简单,我从 5 月份开始学习 R,但我学不会。 如果有人可以帮助我,那就太好了,因为我正在研究的是我的硕士论文。

谢谢

【问题讨论】:

    标签: r function apply


    【解决方案1】:

    假设您的数据名为data,并且列的顺序为cik.noform.typefiling_year,您可以尝试以下操作。

    result <- do.call(rbind, apply(data, 1, function(x) 
                  getSentiment(cik.no = x[1], form.type =x[2], filing_year = x[3])))
    

    同样,这个使用Map 的解决方案也应该可以工作。

    result <- do.call(rbind, Map(getSentiment, data[[1]], data[[2]], data[[3]]))
    

    【讨论】:

    • 非常感谢,也感谢其他这么快回答的人,使用地图的解决方案是最好的。
    【解决方案2】:

    如果您使用矩阵行的索引生成一个向量,您可以将其用作purrr 包中函数map_dfr 的输入。此函数将提供的函数应用于提供的向量的每个元素(此处为行索引)并将生成的 data.frame 绑定在一起。

    test_mat <- matrix(1:9, ncol = 3)
    
    test_fun <- function(a, b, c) {
      data.frame(c1 = a,
                 c2 = 2 * b,
                 c3 = 3 * c)
    }
    
    number_row <- seq_len(nrow(test_mat))
    
    res <- purrr::map_dfr(number_row, ~test_fun(test_mat[.x, 1],
                                                test_mat[.x, 2],
                                                test_mat[.x, 3]))
    res
    #>   c1 c2 c3
    #> 1  1  8 21
    #> 2  2 10 24
    #> 3  3 12 27
    

    reprex package (v0.3.0) 于 2020-09-19 创建

    对于您的函数,将其更改为:

    res <- purrr::map_dfr(number_row, ~getSentiment(cik.no[.x, 1],
                                                    form.type[.x, 2],
                                                    filing_year[.x, 3]))
    

    (假设您的数据中cik.noform.typefiling_year 的顺序)

    【讨论】:

      【解决方案3】:

      您可以使用tidyverse purrr 包中的pmap 函数。输出将是您的函数的返回矩阵列表。然后你可以rbind 一起输出:

      library(tidyverse)
      paramlist <- list(cik.no, form.type, filing.year) # the parameters are vectors
      outputs <- pmap(paramlist, getSentiment)
      final <- do.call(rbind, outputs)
      

      【讨论】:

        猜你喜欢
        • 2015-01-04
        • 1970-01-01
        • 2014-08-12
        • 1970-01-01
        • 2020-08-31
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多