如何用lapply一行代码补全缺失:00并合并数据集变量
One-Liner Solution with
lapply to Fill Missing Seconds and Merge Variables Got it, let's craft that one-liner you're looking for! Here's how you can handle both the :00补全 for v2 and the merge with v1 in a single lapply call:
# Replace df with your actual dataset name df$v3 <- unlist(lapply(seq_len(nrow(df)), function(row_idx) { # Check if v2 already ends with :XX (seconds part) cleaned_v2 <- ifelse(grepl(":\\d{2}$", df$v2[row_idx]), df$v2[row_idx], paste0(df$v2[row_idx], ":00")) # Merge v1 and cleaned v2 paste0(df$v1[row_idx], cleaned_v2) }))
Breakdown of what this does:
- We use
lapplyto iterate over each row index (viaseq_len(nrow(df))) — this lets us access corresponding values ofv1andv2for each row. - The
grepl(":\\d{2}$", ...)check verifies ifv2already has a seconds component (ends with:XXwhere XX are digits). If yes, we keepv2as-is; if not, we append:00. - Finally,
paste0merges the originalv1value with the cleanedv2value, andunlistconverts the list output fromlapplyinto a vector that we can assign tov3.
Example Usage
Suppose your dataset looks like this:
df <- data.frame( v1 = c("2024-05-20", "2024-05-21", "2024-05-22"), v2 = c("08:45", "13", "17:30:00"), stringsAsFactors = FALSE )
Running the one-liner will result in df$v3 being:
[1] "2024-05-2008:45" "2024-05-2113:00" "2024-05-2217:30:00"
If you want a separator (like a space) between v1 and v2, just swap paste0 with paste(df$v1[row_idx], cleaned_v2, sep = " ").
内容的提问来源于stack exchange,提问作者gaspers
相关产品推荐
相关产品推荐

