我是R的新手,我正在尝试编写一个功能,可以在不同的数据帧中规范化我的数据。
规范化过程非常简单,我只是将我想要的数字除以每个对象的种群大小(存储在表格总体中)。 要知道哪个对象与一个对象有关,我尝试使用存储在第一列中每个数据帧中的ID。
我想这样做是因为人口数据框中的某些对象在数据框中没有相应的对象要进行规范化,比如说,数据框有时会有较少的对象。
通常情况下,我会建立一个关系数据库(我试过),但这样做对我没用。所以我试图关联函数中的对象,但函数不起作用。也许你们中的某个人有这方面的经验,可以帮助我。
所以我写这个函数的尝试是:
# Load Tables
# Agriculture, Annual Crops
table.annual.crops <-read.table ("C:\\Users\\etc", header=T,sep=";")
# Agriculture, Bianual and Perrenial Crops
table.bianual.crops <-read.table ("C:\\Users\\etc", header=T,sep=";")
# Fishery
table.fishery <-read.table ("C:\\Users\\etc", header=T,sep=";")
# Population per Municipality
table.population <-read.table ("C:\\Users\\etc", header=T,sep=";")
# attach data
attach(table.annual.crops)
attach(table.bianual.crops)
attach(table.fishery)
attach(table.population)
# Create a function to normalize data
# Objects should be related by their ID in the first column
# Values to be normalized and the population appear in the second column
funktion.norm.percapita<-function (x,y){if(x[,1]==y[,1]){x[,2]/y[,2]}else{return("0")}}
# execute the function
funktion.norm.percapita(table.annual.crops,table.population)
答案 0 :(得分:5)
让我们从附加步骤开始......为什么?它通常是不必要的,可以让你陷入困境!特别是因为你的人口data.frame和你的庄稼data.frame都有Geocode作为一列!
根据评论中的建议,您可以使用merge
。默认情况下,这将使用相同名称的列组合data.frames。您可以指定要与by
参数合并的列。
dat <- merge(table.annual.crops, table.population)
dat$crop.norm <- dat$CropValue / dat$Population
您的功能不起作用的原因?查看if
statemnt的结果。
table.annual.crops[,1] == table.population[,1]
给出一个布尔值矢量,它将回收较短的矢量。如果您的数据非常大(大约数百万行),merge
函数可能会很慢。如果是这种情况,请查看data.table
包并改为使用其合并功能。