【问题标题】:r create a column that contains the objects names inside a lapply functionr 在 lapply 函数中创建一个包含对象名称的列
【发布时间】:2014-03-09 17:25:13
【问题描述】:

我想在 lapply 函数中创建一个包含对象名称的列,作为代理,我将其称为 name.of.x.as.strig.function(),不幸的是我不知道该怎么做,可能是assign、do.call 和paste 的组合。但到目前为止,使用这个功能只会让我陷入更深的麻烦,我很确定还有一个更像 R 的解决方案。

# generates a list of dataframes, 
data <- list(data.frame(c(1,2),c(3,3)),data.frame(c(1,2),c(3,3)),data.frame(c(1,2),c(3,3)),data.frame(c(1,2),c(3,3)))

# assigns names to dataframe
names(data) <- list("one","two", "tree", "four")

# subsets the second column into the object data.anova
data.anova <- lapply(data, function(x){x <- x[[2]];                                        
                                       return(matrix(x))})

这应该允许我在数据框中为列表中的所有矩阵创建一个包含其名称的列

data.anova <- lapply(data, function(x){    
    x$id <- name.of.x.as.strig.function(x)
    return(x)})

我想找回:

3 one
3 one

3 two
3 two

...

非常感谢任何输入。

搜索历史:将对象名称检索为字符串的函数,R 获取 lapply 中的对象名称...

【问题讨论】:

    标签: r lapply


    【解决方案1】:

    难道你只是在找stack

    stack(lapply(data, `[[`, 2))
    #   values  ind
    # 1      3  one
    # 2      3  one
    # 3      3  two
    # 4      3  two
    # 5      3 tree
    # 6      3 tree
    # 7      3 four
    # 8      3 four
    

    (或者,使用您原来的方法:stack(lapply(data, function(x) {x &lt;- x[[2]]; x}))

    如果是这种情况,“reshape2”中的melt 也可以。

    【讨论】:

      【解决方案2】:

      遍历data.anova 的索引,并使用它来获取数据和名称:

      data.anova <- lapply(seq_along(data.anova), function(i){    
        x <- as.data.frame(data.anova[[i]])
        x$id <- names(data.anova)[i]
        return(x)})  
      

      这会产生:

      # [[1]]
      #   V1  id
      # 1  3 one
      # 2  3 one
      
      # [[2]]
      #   V1  id
      # 1  3 two
      # 2  3 two
      
      # [[3]]
      #   V1   id
      # 1  3 tree
      # 2  3 tree
      
      # [[4]]
      #   V1   id
      # 1  3 four
      # 2  3 four
      

      【讨论】:

      • 如果这是他们所追求的,我通常会做更像lapply(names(data), function(x) data.frame(ID = x, value = data[[x]][[2]])) 的事情......不过,完全一样的想法,所以+1 :-)
      • @AnandaMahto,一如既往,给出明确的答案!
      猜你喜欢
      • 2020-10-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-05-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-06-23
      相关资源
      最近更新 更多