R语言报错:$运算符对原子向量无效,求解决方案
$ operator is invalid for atomic vectors错误 Hey there! Let's break down why you're running into this error and fix it right away.
What's causing the error?
The message Error in reviews2$Rating : $ operator is invalid for atomic vectors means your reviews2 object has stopped being a data frame—instead, it's now an atomic character vector. Here's how that happened:
After you used unite() to combine Title and Review.Text, reviews2 was still a data frame with all your original columns (including Rating). But when you ran reviews2 <- gsub("NA", "", reviews2), you passed the entire data frame to gsub()—a function that only works on vectors. R forced the whole data frame into a single character vector to make this work, and in doing so, you lost the data frame structure needed to use $ to access columns.
How to fix it
Let's adjust your code to keep reviews2 as a data frame while cleaning up the text:
Clean only the combined text column
Instead of applyinggsub()to the entire data frame, target just the column you created withunite():# Keep reviews2 as a data frame after uniting columns reviews2 <- reviewscl %>% unite(combined_text, Title, Review.Text, sep=" ") # Apply gsub only to the new combined text column reviews2$combined_text <- gsub("NA", "", reviews2$combined_text)I renamed the united column to
combined_textfor clarity, but you can stick with the original name as long as you target that specific column.Convert Rating to numeric safely
Now thatreviews2is still a data frame, you can access theRatingcolumn without issues:reviewStars <- as.numeric(reviews2$Rating) reviews3 <- cbind(reviews2, reviewStars)
Quick extra tip
If you're trying to remove actual NA values (not just the string "NA") from your data, use na.omit() instead of gsub(). It will drop rows with missing values entirely:
reviews2 <- reviews2 %>% na.omit()
内容的提问来源于stack exchange,提问作者Kitty123

