I'm attempting to use the "where" function in R within a loop to pick out a certain row from two datasets based on a matching element, and then make a scatterplot of the two. They code sample below provides the row names of the two dataframes and the loop. Each dataframe contains more counties than are listed in "mycounties".
I have used the "where" function in a loop exactly like this before, but this time R is returning the error message that "where" doesn't exist? I know "where" exists! My question is, how do I make R recognize this "where" structure, or is there a better way to pick out the rows I want to plot?
> names(dts) [1] "county" "Freq125" "Freq126" "Freq127" "Freq128" "Freq129" "Freq130" "Freq131" "Freq132" "Freq133" "Freq134" "Freq135" "Freq136" "Freq137" [15] "Freq138" "Freq139" "Freq140" "Freq141" "Freq142" "Freq143" "Freq144" "Freq145" "Freq146" "Freq147" "Freq148" "Freq149" "Freq150" "Freq151" [29] "Freq152" "Freq153" "Freq154" "Freq155" "Freq156" "Freq157" "Freq158" "Freq159" "Freq160" "Freq161" "Freq162" "Freq163" "Freq164" "Freq165" [43] "Freq166" "Freq167" "Freq168" "Freq169" "Freq170" "Freq171" > names(pm) [1] "county" "pm125m" "pm126m" "pm127m" "pm128m" "pm129m" "pm130m" "pm131m" "pm132m" "pm133m" "pm134m" "pm135m" "pm136m" "pm137m" "pm138m" [16] "pm139m" "pm140m" "pm141m" "pm142m" "pm143m" "pm144m" "pm145m" "pm146m" "pm147m" "pm148m" "pm149m" "pm150m" "pm151m" "pm152m" "pm153m" [31] "pm154m" "pm155m" "pm156m" "pm157m" "pm158m" "pm159m" "pm160m" "pm161m" "pm162m" "pm163m" "pm164m" "pm165m" "pm166m" "pm167m" "pm168m" [46] "pm169m" "pm170m" "pm171m" > > mycounties = c("beaufort", "bertie", "bladen", "camden", "carteret", "chowan", "craven", + "cumberland", "currituck", "dare", "duplin", "gates", "greene", "harnett", "hyde", + "jones", "lenoir", "new hanover", "onslow", "pamlico", "pasquotank", "pender", "perquimans", "pitt", "robeson", "sampson", "tyrrell", "washington") > > LOOP > for (i in 1:length(mycounties)) { + x = pm[where(pm$county == mycounties[i]),2:48] + y = dt[where(dts$county == mycounties[i]),2:48 ] + plot( x, y, main=paste("HYSPLIT & ED Visits", counties[i], sep=""), + xlab="HYSPLIT", ylab="ED Visits", pch=19) + } Error in `[.data.frame`(pm, where(pm$county == mycounties[i]), 2:48) : could not find function "where" 02 Answers
Like Jeff and the comments have said, there is no where function. which is the R version.
However, in this example you don't need which at all:
x <- pm[pm$county == mycounties[i], 2:48] y <- dt[dt$county == mycounties[i], 2:48] Also in your example if statement:
if (mat$county[i] %in% dt5$county)) { mat[i,2:58] = dt5[dt5$county == mat$county[i], 2:58] } That is assuming your dt5$county has only one matching county for each mat$county[i]. Otherwise you'll get an error.
Are you trying to refer to the which() function?