gpt4 book ai didi

r - 创建大型数据帧

转载 作者:行者123 更新时间:2023-12-04 10:59:05 25 4
gpt4 key购买 nike

假设我想从头开始生成一个大型数据框。

使用 data.frame 函数是我通常创建数据框的方式。
但是,如下所示的 df 非常容易出错且效率低下。

那么有没有更有效的方法来创建以下数据框。

df <- data.frame(GOOGLE_CAMPAIGN=c(rep("Google - Medicare - US", 928), rep("MedicareBranded", 2983),
rep("Medigap", 805), rep("Medigap Branded", 1914),
rep("Medicare Typos", 1353), rep("Medigap Typos", 635),
rep("Phone - MedicareGeneral", 585),
rep("Phone - MedicareBranded", 2967),
rep("Phone-Medigap", 812),
rep("Auto Broad Match", 27),
rep("Auto Exact Match", 80),
rep("Auto Exact Match", 875)),
GOOGLE_AD_GROUP=c(rep("Medicare", 928), rep("MedicareBranded", 2983),
rep("Medigap", 805), rep("Medigap Branded", 1914),
rep("Medicare Typos", 1353), rep("Medigap Typos", 635),
rep("Phone ads 1-Medicare Terms",585),
rep("Ad Group #1", 2967), rep("Medigap-phone", 812),
rep("Auto Insurance", 27),
rep("Auto General", 80),
rep("Auto Brand", 875)))

哎呀,这是一些“糟糕”的代码。如何以更有效的方式生成这个“大”数据框?

最佳答案

如果您获得该信息的唯一来源是一张纸,那么您可能不会得到比这更好的信息,但您至少可以将所有这些信息合并到一个 rep 中。调用每一列:

#I'm going to cheat and not type out all those strings by hand
x <- unique(df[,1])
y <- unique(df[,2])

#Vectors of the number of times for each
x1 <- c(928,2983,805,1914,1353,635,585,2967,812,27,955)
y1 <- c(x1[-11],80,875)

dd <- data.frame(GOOGLE_CAMPAIGN = rep(x, times = x1),
GOOGLE_AD_GROUP = rep(y, times = y1))

这应该是相同的:
> all.equal(dd,df)
[1] TRUE

但是,如果这些信息已经以某种方式存在于 R 中的数据结构中,而您只需要对其进行转换,那可能会更容易,但我们需要知道该结构是什么。

关于r - 创建大型数据帧,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7211329/

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