使用for循环重构数据框:解决get(i) <- trip赋值失效的技术求助
get(i) <- trip Assignment Issue in R Hey there! I see exactly what's going on here. Your loop logic makes total sense, but the problem is that get(i) only returns a copy of the data frame with name i—it doesn't create a reference to the original variable. So when you try get(i) <- trip, you're just assigning to that temporary copy, not the actual variable in your environment. Let's fix this with two solid approaches:
1. Use assign() to Update Original Variables
The assign() function is made for this exact scenario: it lets you assign a value to a variable using its name as a string. Here's how to adjust your loop:
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) assign(i, trip) # This replaces the original variable with your modified trip } }
When you run this, assign(i, trip) takes the modified trip data frame and saves it back to the variable named i in your current environment—exactly what you were trying to do with get(i) <- trip.
2. (Recommended) Manage Data Frames in a List (Cleaner, Safer)
If divvy_trips is a list containing your data frames (instead of a vector of data frame names), working directly within the list is a more idiomatic R approach. It keeps all your related data organized and avoids cluttering your global environment with individual variables. Here's how to do it with lapply:
# Assuming divvy_trips is a list like: divvy_trips <- list(trip1 = df1, trip2 = df2) divvy_trips <- lapply(divvy_trips, function(trip) { if ("starttime" %in% names(trip)) { trip$starttime <- as.character(trip$starttime) trip$stoptime <- as.character(trip$stoptime) } trip # Return the modified (or unmodified) data frame })
After running this, every data frame in divvy_trips will have its starttime and stoptime columns converted to character type (if those columns exist). You can access individual data frames like divvy_trips$trip1 or divvy_trips[[1]] whenever you need them.
Either approach will solve your problem—pick the one that fits how you're organizing your project data best!
内容的提问来源于stack exchange,提问作者Kim

