You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用for循环重构数据框:解决get(i) <- trip赋值失效的技术求助

Fixing the 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.

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.30 21:33:13