使用两个向量作为指示器折叠行的实现方法
Hey there! No worries about being a new poster—we've all been there 😊. Let's fix this for you.
The issue with your original code is that text[x:y] treats your start (x) and end (y) vectors as a single range instead of processing each pair of start-end positions individually. That's why you're not getting the two separate strings you want.
Correct Implementation Using Base R
We can use mapply() to iterate over each pair of start and end indices, collapse the corresponding text elements, then wrap the result in a data frame:
text <- c("cat", "dog", "house", "mouse", "street") x <- c(1, 3) y <- c(2, 5) # Process each start-end pair and collapse the text collapsed_strings <- mapply(function(start_idx, end_idx) { paste(text[start_idx:end_idx], collapse = " ") }, x, y) # Convert to data frame (keep strings as text, not factors) result <- data.frame(collapsed_text = collapsed_strings, stringsAsFactors = FALSE) # View the result print(result)
This will output exactly what you're looking for:
collapsed_text 1 cat dog 2 house mouse street
Alternative Using purrr (Tidyverse Style)
If you prefer using the tidyverse, the map2_chr() function from purrr makes this even more concise:
library(purrr) collapsed_strings <- map2_chr(x, y, ~paste(text[.x:.y], collapse = " ")) result <- data.frame(collapsed_text = collapsed_strings)
Both approaches work by handling each start-end pair separately: for each index i, they take text[x[i]:y[i]], collapse those elements into a single space-separated string, then collect all those strings into a vector that becomes the column of your data frame.
内容的提问来源于stack exchange,提问作者Jo el

