【问题标题】:How to name Dataframes inside a List如何在列表中命名数据框
【发布时间】:2020-01-06 22:59:41
【问题描述】:

我创建了一个基本列表,在这个名为 lista 的列表中(我知道这不是什么大幻想),有 10 个小数据框。 每个数据帧都称为 "numberone","numbertwo",...,"numberten"

当我加入这个名单时,我看不到他们的名字。 但是我可以在工作区(Rstudio)中看到的输出是这样的

以下是代码和我的尝试:

#creating multiple dataframes and a list and then give a title to this dataframes inside the list.

lista = list()
names = c("numberone","numbertwo","numberthree","numberfour","numberfive","numbersix","numberseven","numbereight","numbernine","numberten")

for (i in 1:10) {
  x = rnorm(10)
  df = data.frame(x)
  assign(names[i],df)
  lista[[i]] = df
}


#trying to change manually the names of the dataframes inside the "lista"  list

names(lista[1]) = "number one"
print(names(lista[1]))  #this gives no results

#trying using dput
output = dput(lista[1])

##trying put manually the name in front of the dput output to rename the first dataframe inside lista..
list('numberone'= structure(list(x = c(0.750704535096297, 1.16925878942967, 
                          0.806475114411396, 1.00973486249489, -0.301553383694518, 0.546485320708262, 
                          1.03645444095639, 0.247820396853631, -1.64294545886444, -0.216784798035195
)), class = "data.frame", row.names = c(NA, -10L)))

#this seems to have renamed the first dataframe but, it's not working anyway
lista$numberone

print(names(lista[1])) #still no results

我已经尝试了几乎所有我能做的事情,但是我不能在列表中给这个单一的数据框起名字。

如何命名这些数据框? 谢谢你

【问题讨论】:

    标签: r list dataframe


    【解决方案1】:

    尝试做names(list)

    这里是一个使用空列表的例子

    list_test = vector("list",4)
    names(list_test) = c("A","B","C","D")
    list_test
    
    $A
    NULL
    
    $B
    NULL
    
    $C
    NULL
    
    $D
    NULL
    

    用你的例子,我做到了:

    names(lista) <- names
    

    我得到:

    names(lista)
    [1] "numberone"   "numbertwo"   "numberthree" "numberfour"  "numberfive"  "numbersix"   "numberseven"
    [8] "numbereight" "numbernine"  "numberten"   
    

    【讨论】:

      【解决方案2】:

      我认为您可能希望使用双括号(例如 [[1]])来引用列表中的元素。使用您的示例代码,这将起作用:

      names(lista[[1]]) = "number one"
      print(names(lista[[1]]))  #first element is now called "number one"
      

      您还可以在 Map() 函数中使用 setNames() 函数来重命名数据框列表的每一列。

      lista <-Map(setNames, lista , names)
      lista # each column is now assigned a name from your vector called names
      

      为了尽可能保持代码简洁,最好避免将对象命名为与函数同名。 (您的示例代码使用了一个名为“names”的向量,但也使用了 names() 函数。)

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-09-20
        • 1970-01-01
        • 2017-12-28
        • 1970-01-01
        • 2019-03-27
        • 2014-10-26
        • 1970-01-01
        • 2018-01-04
        相关资源
        最近更新 更多