R语言数据框列已创建,但exists返回false且get调用失败
R Data Frame Column Indirect Reference Issue
Problem Overview
Attempting to indirectly access a data frame column using get(paste0('df$', Selection)) fails to retrieve data, and exists(paste0('df$', Selection)) returns FALSE. However, directly referencing the column with df$Scen_4_2 works correctly. The goal is to dynamically reference columns using generated names.
Reproducible Code Example
times <- 0:365 df <- data.frame(times) for (i in 1:5){ for(j in 3:6){ scen_name = paste("Scen", j, i, sep="_") scen_out <- sample(times) df <- cbind(df, scen_out) colnames(df)[length(df)] <- scen_name } } # 获取用户输入的待查看/绘图变量 Selection <- "Scen_4_2" get(paste0('df$',Selection)))
Root Cause
df$Scen_4_2 is not a standalone variable in the global environment—it’s syntax to access a column inside the df data frame. The get() function only searches for top-level variables, not elements within objects like data frames.
Solutions
- Use bracket notation (recommended for dynamic access):
df[[Selection]] - Use the
getElement()function:getElement(df, Selection) - To check if the column exists, use
Selection %in% colnames(df)instead ofexists()
Fixed Code Example
times <- 0:365 df <- data.frame(times) for (i in 1:5){ for(j in 3:6){ scen_name = paste("Scen", j, i, sep="_") scen_out <- sample(times) df <- cbind(df, scen_out) colnames(df)[length(df)] <- scen_name } } Selection <- "Scen_4_2" # Correct dynamic column access df[[Selection]] # Verify column exists Selection %in% colnames(df)
内容的提问来源于stack exchange,提问作者David Manheim
相关产品推荐
相关产品推荐

