lapply之后从列表返回到data.frame [英] returning from list to data.frame after lapply
问题描述
我有一个关于lapply的非常简单的问题.我正在从STATA过渡到R,我认为有一些非常基本的概念,我不会在R中循环.但是我整个下午都在阅读有关它的内容,无法找到一种合理的方法来完成这一非常简单的事情
I have a very simply question about lapply. I am transitioning from STATA to R and I think there is some very basic concept that I am not getting about looping in R. But I have been reading about it all afternoon and can't figure out a reasonable way to do this very simple thing.
我有三个数据帧df1,df2和df3,它们都具有相同的列名,顺序相同等.
I have three data frames df1, df2, and df3 that all have the same column names, in the same order, etc.
我想一次重命名它们的列.
I want to rename their columns all at once.
我将数据帧放在列表中:
I put the data frames in a list:
dflist <- list(df1, df2, df3)
我希望新名称是什么
varlist <- c("newname1", "newname2", "newname3")
编写一个用varlist中的名称替换名称的函数,然后将其套用在数据帧上
Write a function that replaces names with those in varlist, and lapply it over the data frames
ChangeNames <- function(x) {
names(x) <- varlist
return(x)
}
dflist <- lapply(dflist, ChangeNames)
据我所知,R更改了我放入列表中的数据帧副本的名称,但未更改原始数据帧本身.我希望重命名数据框本身,而不是重命名列表中的元素(被困在列表中).
So, as far as I understand, R has changed the names of the copies of the data frames that I put in the list, but not the original data frames themselves. I want the data frames themselves to be renamed, not the elements of the list (which are trapped in a list).
现在,我可以走了
df1 <- as.data.frame(dflist[1])
df2 <- as.data.frame(dflist[2])
df2 <- as.data.frame(dflist[3])
但这似乎很奇怪.您需要一个循环来取回循环的元素吗?
But that seems weird. You need a loop to get back the elements of a loop?
基本上:将一些数据帧放入列表中并通过lapply在其上运行函数后,如何将它们从列表中移出而又不从第一个平方开始呢?
Basically: once you've put some data frames in a list and run your function on them via lapply, how do you get them back out of the list, without starting back at square one?
推荐答案
如果只想更改名称,在R中就不太难了.请记住,赋值运算符<-
,可以依次应用.因此:
If you just want to change the names, that isn't too hard in R. Bear in mind that the assignment operator, <-
, can be applied in sequence. Hence:
names(df1) <- names(df2) <- names(df3) <- c("newname1", "newname2", "newname3")
这篇关于lapply之后从列表返回到data.frame的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!