假设我想从头开始生成一个大数据帧。
我通常会使用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)))
kes,那是一些“坏”的代码。如何以更有效的方式生成此“大”数据帧?
最佳答案
如果您唯一的信息来源是纸,那么您可能不会比这更好的了,但是您至少可以将所有内容合并到每个列的一个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/