R语言向量元素条件追加需求:无小数点元素合并处理
Alright, let's break down how to solve this problem: we have a character vector where we need to combine consecutive elements only if neither of them contains a decimal point. The merged element should use a dot as a separator, and we need to remove the second element once it's appended to the first.
First, let's confirm the original vector and expected output to make sure we're aligned:
- Original vector:
a = c("135","00","85","6","0.00","6","0.00","0.00","85","61","0.00") - Expected result:
"135.00","85.6","0.00","6","0.00","0.00","85.61","0.00"
Simple Loop-Based Solution
A loop is perfect here because we're modifying the vector as we iterate (we need to skip elements once they're merged). Here's the code that gets the job done:
# Define your original vector a <- c("135","00","85","6","0.00","6","0.00","0.00","85","61","0.00") # Start at the first element i <- 1 # Loop until we reach the second-to-last element while (i < length(a)) { # Check if current AND next element have no decimal points if (!grepl("\\.", a[i]) && !grepl("\\.", a[i+1])) { # Merge them with a dot a[i] <- paste0(a[i], ".", a[i+1]) # Remove the now-redundant next element a <- a[- (i + 1)] # Don't increment i—since we just removed an element, the next candidate is still at i+1 } else { # Move to the next element if no merge happened i <- i + 1 } } # Check the result print(a)
What this code does:
grepl("\\.", x)checks if a string has a decimal point. The!flips it to check for strings without dots.- When we find a pair to merge, we update the current element to be the combined string, then drop the second element. We don't increment
ihere because the element after the merged pair is now in the position we just checked—we need to verify if it should merge with the new current element. - If no merge is needed, we just move to the next element.
Running this will output exactly what you want:
[1] "135.00" "85.6" "0.00" "6" "0.00" "0.00" "85.61" "0.00"
Optional Vectorized Approach (No Loops)
If you prefer avoiding loops (maybe for larger vectors), you can use dplyr and tidyr to group and merge elements. This is a bit more abstract, but works just as well:
library(dplyr) library(tidyr) # Turn the vector into a data frame with helper columns df <- tibble( value = a, position = seq_along(a), has_decimal = grepl("\\.", value) ) # Create groups where consecutive non-decimal elements belong together df <- df %>% mutate(merge_group = cumsum(has_decimal | lag(has_decimal, default = TRUE))) # Merge within each group final_vector <- df %>% group_by(merge_group) %>% summarise( value = ifelse(n() == 2 && all(!has_decimal), paste(value, collapse = "."), value) ) %>% ungroup() %>% pull(value) print(final_vector)
This will also produce the expected result, though the loop version is more straightforward for this specific problem.
内容的提问来源于stack exchange,提问作者NinjaR

