I have a large data set, which I need to split into multiple datasets based on area column and then execute some set of codes for each area and get output data for each area. I was trying to do this using a for loop but it does not seem to work. How can this be achieved. below is the code I was trying -
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
}
Can we do something like this in R. Sorry I am still learning R and not sure about the feasibility. What is the best way to achieve this?
EDIT - SAMPLE DATA
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))]
CODE that I want to replicate for each area ( ref from this link - https://www.r-bloggers.com/fuzzy-string-matching-a-survival-skill-to-tackle-unstructured-information/)
using method2 I want to replicate the code for each area -
#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)