简体   繁体   中英

In R, How to create a table with unique rows from another table and then add new columns to new table

I have a table:

ID    Latitude Longitude Visit_Date
1850  46.72187 -114.7254  7/1/2017
1850  46.72187 -114.7254  12/7/2018
1850  46.72187 -114.7254  6/13/2018
1850  46.72186 -114.7250  6/13/2018
1850  46.72186 -114.7250  6/8/2019
1850  46.72186 -114.7250  10/26/2019

I want to create a table that has a row for each unique lat long and the time frame that the ID was at that lat long. So ideally an output like this:

ID    Latitude Longitude   Start     End
1850  46.72187 -114.7254   7/1/2017  6/13/2018
1850  46.72186 -114.7250   6/13/2018 10/26/2019

I am a little lost on how to accomplish this. I was thinking using the shift() function to subtract rows from another and if the lat long != 0 then that would be a unique lat long. I was also thinking the unique() function would be useful but I'm not sure which direction would be best. Any help will be useful. Thank you!

Using dplyr, you can do summary statistics pretty easily:

df1 %>% 
    mutate(Visit_Date = as.Date(Visit_Date, format = "%m/%d/%Y")) %>% 
    group_by(ID, Latitude, Longitude) %>% 
    summarise(Start = min(Visit_Date), 
              End = max(Visit_Date))

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