【发布时间】:2017-03-13 13:41:56
【问题描述】:
我有一个大型数据集,我需要根据区域列将其拆分为多个数据集,然后为每个区域执行一组代码并获取每个区域的输出数据。我试图使用 for 循环来做到这一点,但它似乎不起作用。这怎么可能实现。下面是我正在尝试的代码 -
for (a in c('10','11','14','20','30','40','50','61','64'))
{
paste0("data3_add_area",a) <- data3_add[AREACODE == a,]
paste0("in_add_area",a) <- in_add[AREA_CODE == a,]
source1 <- paste0("data3_add_area",a)$name
source2 <- paste0("in_add_area",a)$name
.....
paste0("match_",a) <- output
}
我们可以在 R 中做这样的事情吗?抱歉,我还在学习 R,不确定是否可行。实现这一目标的最佳方法是什么?
编辑 - 样本数据
Address1 <- c("786, GALI NO 5, XYZ","rambo, 45, strret 4, atlast, pqr","23/4, 23RD FLOOR, STREET 2, ABC-E, PQR","45-B, GALI NO5, XYZ","HECTIC, 99 STREET, PQR")
AREACODE <- c('10','11','14','20','30')
Year1 <- c(2001:2005)
Address2 <- c("abc, pqr, xyz","786, GALI NO 4 XYZ","45B, GALI NO 5, XYZ","del, 546, strret2, towards east, pqr","23/4, STREET 2, PQR","abc, pqr, xyz","786, GALI NO 4 XYZ","45B, GALI NO 5, XYZ","del, 546, strret2, towards east, pqr","23/4, STREET 2, PQR")
Year2 <- c(2001:2010)
AREA_CODE <- c('10','11','14','20','30','40','50','61','64')
data3_add <- data.table(Address1,Year1,AREACODE)
in_add <- data.table(Address2,Year2,AREA_CODE)
in_add [,unique_id := sprintf("%06d", 1:nrow(in_add))]
我想为每个区域复制的代码(来自此链接的参考 - https://www.r-bloggers.com/fuzzy-string-matching-a-survival-skill-to-tackle-unstructured-information/)
使用method2我想复制每个区域的代码-
#install.packages('stringdist')
library(stringdist)
distance.methods<-c('osa','lv','dl','hamming','lcs','qgram','cosine','jaccard','jw')
dist.methods<-list()
for(m in 1:length(distance.methods))
{
dist.name.enh<-matrix(NA, ncol = length(source2.devices$name),nrow = length(source1.devices$name))
for(i in 1:length(source2.devices$name)) {
for(j in 1:length(source1.devices$name)) {
dist.name.enh[j,i]<-stringdist(tolower(source2.devices[i,]$name),tolower(source1.devices[j,]$name),method = distance.methods[m])
#adist.enhance(source2.devices[i,]$name,source1.devices[j,]$name)
}
}
dist.methods[[distance.methods[m]]]<-dist.name.enh
}
match.s1.s2.enh<-NULL
for(m in 1:length(dist.methods))
{
dist.matrix<-as.matrix(dist.methods[[distance.methods[m]]])
min.name.enh<-apply(dist.matrix, 1, base::min)
for(i in 1:nrow(dist.matrix))
{
s2.i<-match(min.name.enh[i],dist.matrix[i,])
s1.i<-i
match.s1.s2.enh<-rbind(data.frame(s2.i=s2.i,s1.i=s1.i,s2name=source2.devices[s2.i,]$name, s1name=source1.devices[s1.i,]$name, adist=min.name.enh[i],method=distance.methods[m]),match.s1.s2.enh)
}
}
# Let's have a look at the results
library(reshape2)
matched.names.matrix<-dcast(match.s1.s2.enh,s2.i+s1.i+s2name+s1name~method, value.var = "adist")
View(matched.names.matrix)
【问题讨论】:
-
您能提供一些可重现的数据吗?例如
dput(head(data2_add, 20)),也可能是in_add。 -
也许您正在寻找
split,它可以根据某个向量的值将data.frame 拆分为data.frames 列表。myList <- split(data3_add, data3_add$AREACODE)。 gregor 对this post 的回答也可能有助于处理 data.frames 列表。 -
@Frank,感谢您指出。我已经更新了示例代码。
标签: r for-loop split data.table