[R] Comparing the components of a data frame without levels interfering
Petr PIKAL
petr.pikal at precheza.cz
Thu Oct 13 06:38:44 CEST 2011
Hi
> *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)
> }
> }
> }
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
>
> 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.
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide
http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
More information about the R-help
mailing list