gpt4 book ai didi

r - 将数据帧列表传递到循环中以同时组合和更改标题

转载 作者:行者123 更新时间:2023-12-05 00:22:13 25 4
gpt4 key购买 nike

我有一组具有不同标题的 dfs,我需要逐行绑定(bind):我希望更改 cols 的名称,以便每个标题具有相同的标题。

df1

 name, score
smith, 3
smith, 7
smith, 5

df2
 type, price
food, 3
food, 5
food, 2.6

我想将其组合起来,以便每个标题都具有相同的标题并按行组合。我有 32 个这些数据框都有不同的标题,所以我打算使用循环

我列出了 dfs
 groups <- c(df1, df2, df3, etc)

然后尝试合并成一个空的df:
 new_df <- data.frame(words=character(),numbers=numeric())

for (i in 1:length(groups))
{
x <- data.frame(words=character(),numbers=numeric())
x[,1] <- groups[i]
x[,2] <- groups[i+1]
new_df <- rbind(new_df, x)
}

不幸的是,它只是返回一个带有一堆警告的空 df。谁能告诉我如何纠正这个问题?我希望 new_df 是;
 words, numbers
smith, 3
smith, 7
smith, 5
food, 3
food, 5
food, 2.6

我相信这对于比我有更多经验的人来说很容易。谢谢

最佳答案

为什么你的 32 个 data.frames 在 list 中不能很好地结合在一起? ?首先从野外捕捉它们:

dfList <- mget(paste0("df", 1:32))

然后你可以使用 lapply :
dfList <- lapply(dfList, setNames, nm = c("words", "numbers"))

最后是你 rbind他们:
DF <- do.call(rbind, dfList)

关于r - 将数据帧列表传递到循环中以同时组合和更改标题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30352418/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com