Home > database >  Recreate dataframe to use for-loop
Recreate dataframe to use for-loop

Time:10-31

I am learning student and doing capstone work. This is part of my code.

   for(i in divvy_trips){
       trip<-get(i)
       if ("starttime" %in% names(trip)){
            trip$starttime <- as.character(trip$starttime)
            trip$stoptime <- as.character(trip$stoptime)
       get(i) <- trip

In this code, I want use in divvy_trips that contain data frames and fix some column as character and recreate dataframe as same name. but

get(i) <- trip

deosn't work. so I need some help to work this objective but another method.

CodePudding user response:

It is not intended as a solution but as a tip (as I cannot really understand what you're trying to achieve): your last line should be assign(i, trip) (or simething similar) instead of get(i) <- trip.

CodePudding user response:

If your data structure is indeed a list of data.frames like this

trip_1 <- data.frame(a = 1:10, b = 11:20)
trip_2 <- data.frame(a = 91:100, starttime = 1:10, stoptime = 11:20)

divvy_trip <- list(trip_1 = trip_1, trip_2 = trip_2)

You could use lapply to solve your problem:

divvy_trip <- lapply(divvy_trip, 
                     function(dat) {
                       if ("starttime" %in% names(dat)) {
                         dat$starttime <- as.character(dat$starttime)
                         dat$stoptime <- as.character(dat$stoptime) 
                         }
                       dat
                       }
                     )

This changes the starttime and stoptime column of the data.frame trip_2 into character:

class(divvy_trip[["trip_2"]][["starttime"]])
#> [1] "character"
  • Related