R语言中使用CrossTable分析Likert量表烟酒消费相关性时出现‘object not found’错误的求助
Hey there! As someone who’s been in your shoes as an R newbie, I totally get how frustrating this error can feel when you’re just trying to dive into your data. Let’s break down the most common reasons you’re seeing Error in CrossTable(...) : object 'Do.you.consume.alcohol' not found and how to fix each one:
1. Your survey data isn’t loaded into R yet
R can’t find variables that aren’t in its working environment. First, you need to import your Likert scale data into R. For example, if your data is saved as a CSV file, run this (replace the file path with your actual file location):
# Import CSV data (adjust the file path to match your file) survey_data <- read.csv("path/to/your/survey_data.csv")
If you’re using an Excel file, you’ll need the readxl package:
install.packages("readxl") library(readxl) survey_data <- read_excel("path/to/your/survey_data.xlsx")
After importing, run names(survey_data) to check if your target variables appear in the list of column names.
2. You’re not specifying the data frame containing your variables
Even if your data is loaded, R won’t automatically look inside the data frame for your variables. You have two simple fixes for this:
- Use the
$operator to reference variables directly from the data frame:CrossTable(survey_data$Do.you.consume.alcohol, survey_data$Do.you.smoke.cigarettes, chisq = TRUE, expected = TRUE) - Use
with()to tell R to look inside the data frame for the variables:with(survey_data, CrossTable(Do.you.consume.alcohol, Do.you.smoke.cigarettes, chisq = TRUE, expected = TRUE))
3. You misspelled the variable name
R is case-sensitive and fussy about punctuation. Double-check that the variable name in your code matches exactly what’s in your dataset. For example:
- If your dataset uses underscores instead of dots (
Do_you_consume_alcohol), your code needs to match that - A tiny typo like
Do.you.consume.alchohol(missing an 'o') will also trigger this error
4. You haven’t loaded the gmodels package
The CrossTable() function isn’t part of base R—it lives in the gmodels package. You need to install it once, then load it every time you start R:
# Install the package (only run this once) install.packages("gmodels") # Load the package (run this every time you use CrossTable) library(gmodels)
Full Working Example
Putting it all together, here’s a step-by-step script you can adapt to your data:
# Install and load required packages install.packages("gmodels") library(gmodels) # Import your survey data survey_data <- read.csv("your_survey_data.csv") # Verify your variables exist in the dataset names(survey_data) # Run the cross table analysis CrossTable(survey_data$Do.you.consume.alcohol, survey_data$Do.you.smoke.cigarettes, chisq = TRUE, expected = TRUE)
This should resolve the "object not found" error and let you analyze the relationship between your drinking and smoking variables.
内容的提问来源于stack exchange,提问作者jim halpert

