基于条件为DataFrame变量添加前缀并创建标记变量
Hey there! Since you already have the logical vector inds that flags which rows had their RingNo prefixed with "x", you can reuse this to efficiently create your Comment column — perfect for your large 200k+ row dataset to avoid redundant calculations.
Method 1: Reuse Your Existing inds Vector (Most Efficient)
Since you already calculated inds <- nchar(df$RingNo) == 6 to identify rows needing the prefix, just use this vector to populate the Comment column directly:
# Initialize Comment column with empty strings df$Comment <- "" # Assign the comment only to rows that were prefixed df$Comment[inds] <- "Prefixed with an x"
Method 2: One-Liner with ifelse
If you prefer a more concise approach, you can use ifelse to handle the assignment in a single line:
df$Comment <- ifelse(inds, "Prefixed with an x", "")
Why This Works
Reusing the existing inds vector is better than recalculating (e.g., checking if RingNo starts with "x") because:
- It’s more accurate: You know exactly which rows were modified, avoiding edge cases where a
RingNomight have naturally started with "x". - It’s faster: No need to re-run
nchar()on 200k+ rows again, saving computation time.
Final Result Example
Place Book.Number RingNo Comment
1 WYT 2020#01 x603701 Prefixed with an x
2 WYT 2020#01 x603701 Prefixed with an x
3 WYT 2020#01 x603701 Prefixed with an x
4 WYT 2020#01 x603702 Prefixed with an x
5 WYT 2020#01 x603703 Prefixed with an x
6 WYT 2020#01 AFH5490
内容的提问来源于stack exchange,提问作者McMahok

