【问题标题】:How to count number of rows in all dataframes that exist in R environment如何计算 R 环境中存在的所有数据框中的行数
【发布时间】:2018-07-31 07:12:34
【问题描述】:

我在 R 环境中创建了数据框。现在我想计算每个数据帧上的行数,并将它们与它们的名称一起存储在一个单独的数据帧中。我已经试过了

number of rows each data frame in a list

How to count rows?

但这些都不适合我。

【问题讨论】:

  • 将所有数据帧存储在一个列表中:dfrs <- list(df1, df2, df3,...) 计数行:dfrs.nrows <- sapply(dfr, nrow)。否则,您需要提供对代码/数据的更多见解。

标签: r dataframe


【解决方案1】:

我们可以用ls()遍历环境中的所有对象,只选择那些属于class“data.frame”的对象,然后创建一个新的数据框。

data.frame(do.call("rbind", lapply(ls(), function(x) {
    obj = get(x)
   if (class(obj) == "data.frame")
     c(name = x, rows = nrow(obj))
})))

#These are the dataframes in my environment.
#         name rows
#1 complete_df   50
#2          df   50
#3        melt   24
#4      new_df   50

【讨论】:

    【解决方案2】:

    下面呢?

    env_objs = ls();
    sapply(env_objs,function(x) {
        if(class(get(x)) == "data.frame") {
          return(nrow(get(x))) 
       } 
      });
    

    【讨论】:

    • 谢谢你的作品。我还发现了另一个 yas ZZ =ls() AY=sapply(ZZ, function(x) {return(nrow(get(x)))}) 我之前没有使用 get(x)
    猜你喜欢
    • 2022-11-07
    • 1970-01-01
    • 2018-06-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-21
    • 1970-01-01
    相关资源
    最近更新 更多