R语言:如何通过for循环合并psw_list中段落的单词?
The issue with your for loop is a small syntax error—you’re mixing up how to access list elements by index. Here’s how to resolve it:
Why Your Original Loop Fails
The $ operator is designed to access named list elements directly (like psw_list$p1), but when using an index variable (i), you need to use double brackets [[i]] instead of $[i]. The $[i] syntax is invalid in R, which causes the "unexpected '['" error.
Corrected For Loop
Replace psw_list$[i] with psw_list[[i]] to properly access each element by index:
for (i in seq_along(psw_list)) { print(paste(psw_list[[i]], collapse = " ")) }
Saving Results Instead of Printing
If you want to store the merged strings for later use (instead of just printing them), initialize an empty list first:
# Create an empty list to hold merged paragraphs merged_paragraphs <- vector("list", length(psw_list)) for (i in seq_along(psw_list)) { merged_paragraphs[[i]] <- paste(psw_list[[i]], collapse = " ") } # Access merged paragraphs like merged_paragraphs[[1]]
More Idiomatic R Approach (No For Loop Needed)
In R, using functional programming functions like lapply is often cleaner than manual for loops. This does the same task in one line:
merged_paragraphs <- lapply(psw_list, paste, collapse = " ")
If you prefer a character vector (instead of a list) of merged paragraphs, use sapply:
merged_paragraphs_vec <- sapply(psw_list, paste, collapse = " ")
内容的提问来源于stack exchange,提问作者djc1223

