Skip to content

Comparing the components of a data frame without levels interfering

4 messages · swonder03, PIKAL Petr, Jeff Newmiller

#
*Bottom Line: How can I compare the individual components of two data frames
with different row lengths without the levels interfering?*

Example: I have two data frames to those respectively named 'dfCity' and
'dfState' that have the following output:

dfCity
 
     Name       City 
1    Bill        Detroit 
2    Jody      Chicago
3    Frank    Memphis 
4    Ron       Houston 

dfState

     Name       State
1    Bill        Michigan
2    Frank    Tennessee  

I have an if statement that is trying to compare the individual's names and
combine the data from the two different data frames to produce some output: 
 
for(j in 1:length(row.names(dfState))){
			for(k in 1:length(row.names(dfCity))){
				if(dfCity[k,1] == dfState[j,1]){
					cityState <- paste(dfCity[k,2], ", ", dfState[j,2], sep= "") 
					print(dfCity[1, j], " is from ", cityState)
				}
			}
		}

However, when I run it I get the error /Error in Ops.factor(dfState[2, 1],
dfCity[4, 1]) : level sets of factors are different/ due to the levels in
the data frames. *How can I compare the individual components of the data
frame without the levels interfering? *

--
View this message in context: http://r.789695.n4.nabble.com/Comparing-the-components-of-a-data-frame-without-levels-interfering-tp3900502p3900502.html
Sent from the R help mailing list archive at Nabble.com.
#
Hi
frames
and
output:
"")
What about first merge two data frames

mergedDF <- merge(dfCity, dfState, all=TRUE)

and after that you can do

cityState <- paste(mergedDF$City, ", ", mergedDF$State, sep= "")

or anything you want.

Regards
Petr
1],
in
data
http://r.789695.n4.nabble.com/Comparing-the-
components-of-a-data-frame-without-levels-interfering-tp3900502p3900502.html
http://www.R-project.org/posting-guide.html
#
Thank you both. For my purposes I need the for statement. I looked into merge
but what I wound up doing was installing the package 'compare' and using the
if statement /if((compare(dfCity[k,1], dfState[j,1],
dropLevels=TRUE)==TRUE){do something}/. This seemed to behave the way I
wanted. 

--
View this message in context: http://r.789695.n4.nabble.com/Comparing-the-components-of-a-data-frame-without-levels-interfering-tp3900502p3903171.html
Sent from the R help mailing list archive at Nabble.com.