简体   繁体   English

使用 lapply 为数据框列表设置列名?

[英]Using lapply to set column names for a list of data frames?

I'm pretty new to R but I'm trying to create a list of data frames and then give them all the same headers in a loop.我对 R 很陌生,但我正在尝试创建一个数据帧列表,然后在循环中为它们提供所有相同的标题。 The plan is to then fill the columns with data from a bunch of messy data files and then bind the small data frames all a single data frame.计划是用一堆杂乱的数据文件中的数据填充列,然后将小数据帧绑定到一个数据帧。 However, I'm stuck on assigning the column names.但是,我坚持分配列名。 I did first try a for loop but saw other answers saying that was the newbie way to do it.我确实首先尝试了一个 for 循环,但看到其他答案说这是新手的做法。

This is what I have right now but when I run it the columns don't update:这就是我现在所拥有的,但是当我运行它时,列不会更新:

a <- data.frame(matrix(ncol=5, nrow=1))
b <- data.frame(matrix(ncol=5, nrow=1))
c <- data.frame(matrix(ncol=5, nrow=1))
d <- data.frame(matrix(ncol=5, nrow=1))

List <- list(a, b, c, d)
headers <- c("First Name","Last Name","Date","Zip Code", "blah")

lapply(List, setNames, nm = headers)

I think I'm missing something about how data frames are updated in R because I do get a print out of 4 empty data frames with the right column names.我想我遗漏了一些关于如何在 R 中更新数据帧的信息,因为我确实打印出了 4 个具有正确列名的空数据帧。 So the function is applying to something.所以 function 适用于某事。 But it's not updating my list and I'm failing to understand why.但它没有更新我的列表,我不明白为什么。

Thank you!谢谢!

We can set column names using,我们可以使用设置列名,

List = lapply(List, function(x) `colnames<-`(x, headers))

It seems you want to update the original dataframes.您似乎想更新原始数据框。 In that case, your list MUST be named.在这种情况下,您的列表必须命名。 ie check the code below.即检查下面的代码。

List <- list(a = a, b = b, c = c, d = d)
list2env(lapply(List, setNames, nm = headers), globalenv())

Now if you call a you will note that it has been updated.现在,如果您调用a ,您会注意到它已更新。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM