简体   繁体   中英

How can I code a for loop that grabs data from dataframe1 and adds it to dataframe2?

I want to achieve a for loop that creates a new column in Dataframe2 that contains for all òbservation2 matching latitude coordinates from Dataframe1 .

observation1 <- c("ABC", "CBA", "BCA")
latitude <- c(12.4, 34.5, 22.34)
Dataframe1 <- data.frame(observation1, latitude)

observation2 <- c("BCA", "ABC", "CBA")
countries <- c("Uk", "US", "Brazil")
Dataframe2 <- data.frame(observation2, countries)

OK, so if it is a homework, here is how one would do that with a for loop.

First, we need to make a column for latitude in the second data frame:

Dataframe2$latitude <- NA

We fill it with NA 's to easily see if something goes wrong.

Next, what are you going to loop over? Well, you need to match observations from Dataframe2 to observations from Dataframe1, so it would be natural to loop over rows of Dataframe2:

for(1 in 1:nrow(Dataframe2)) {
    o <- Dataframe2$observation2[i]
    ... # something
}

OK, but if you have the observation o , how do you find a matching observation from Dataframe1? You can see which of the observations in Dataframe1 are equal to o , but what if there are more than 2 identical observations, like 'ABC' twice in Dataframe1? A better idea is to use match:

idx <- match(o, Dataframe1$observation1)

It returns the index of the first observation in Dataframe1 which matches o . Using this index we can get the latitude:

Dataframe1$latitude[idx]

Hope you can put it all together on your own!

That said, if you look closely at match , you will see that the for loop business is a major waste of time (and dplyr here might be an overkill), because instead of all these lines of code you can do simply

Dataframe2$latitude <- Dataframe1$latitude[ match(Dataframe2$observation2, Dataframe1$observation1) ]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM