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

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 of exists()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.14 17:40:01