如何处理谷歌工作表追加行时的「Error: all(lengths == 1L | lengths == n) is not TRUE」报错?
Error: all(lengths == 1L | lengths == n) is not TRUE When Appending to Google Sheets Hey there! Let’s break down this error and get your row appended successfully. That specific error is super common when using the googlesheets4 package in R to add data to Google Sheets, and it almost always boils down to a mismatch between your input data structure and the sheet’s table layout.
Common Causes & Fixes
Let’s walk through the most likely issues and how to fix them:
1. Your input data isn’t formatted as a matching data frame
If you tried passing a simple vector like c(12,23,34) directly to sheet_append(), that’s the problem. The function expects a data frame where each column corresponds exactly to the columns in your Sheet1 (a1, a2, a3).
2. Column names don’t match exactly
Even a tiny typo (like A1 instead of a1) or missing columns will trigger this error, since googlesheets4 checks that your input columns align with the sheet’s columns.
Working Code Example
Here’s the correct way to structure your code to append the row:
# Load the googlesheets4 package (install first if you haven't: install.packages("googlesheets4")) library(googlesheets4) # Authenticate with your Google account (only needed once per session) gs4_auth() # Create a data frame with matching column names and your values new_record <- data.frame( a1 = 12, a2 = 23, a3 = 34, stringsAsFactors = FALSE ) # Append the row to your sheet sheet_append( ss = "database", # Use your sheet's name, or full URL if there are duplicates data = new_record, sheet = "Sheet1" )
Quick Checks to Avoid Future Errors
- Double-check that your Sheet1 starts at A1 with exactly the column names
a1,a2,a3(no extra empty columns or hidden rows messing with the table structure). - If your sheet has filters or frozen rows enabled, temporarily turn them off before appending—sometimes these interfere with the function’s ability to detect the table boundaries.
内容的提问来源于stack exchange,提问作者Rodrigo Guinea

