基于条件为数据框列值添加字符的R代码修正问题
Hey there! Let's break down why your original for loop isn't giving you the expected result, and go through the right ways to get what you need.
The Problem with Your Original Loop
Your current loop iterates over each value in MyVector, and every time it runs, it overwrites the entire Numbers_2 column. By the last iteration (when Nr = "85"), since 85 exists in MyData$Numbers_2, the code applies the L_N prefix to the whole column. That's why all your values end up with L_N—the final loop iteration overrides everything before it.
Fix 1: Corrected For Loop
Instead of looping through MyVector, we should loop through each row of your data frame to check individual values:
# Create Dataframe MyData <- data.frame(Numbers=c(85,84,7,9,82,5,81,80,10)) MyVector <- c("80","81","82","83","84","85") # Initialize the new column with character values MyData$Numbers_2 <- as.character(MyData$Numbers) # Loop through each row to apply the correct prefix for (i in 1:nrow(MyData)) { if (MyData$Numbers_2[i] %in% MyVector) { MyData$Numbers_2[i] <- paste("L_N", MyData$Numbers_2[i], sep = "") } else { MyData$Numbers_2[i] <- paste("L_", MyData$Numbers_2[i], sep = "") } }
This way, we only modify the specific row we're checking, instead of overwriting the entire column each time.
Fix 2: Vectorized Approach (Recommended!)
R is built for vectorized operations, which are faster and more concise than loops. Your provided ifelse solution is perfect for this:
MyData$Numbers_2 <- with(MyData, ifelse(Numbers %in% MyVector, paste0("L_N", Numbers), paste0("L_", Numbers)))
Numbers %in% MyVectorcreates a logical vector where each entry isTRUEif the corresponding number is inMyVector, andFALSEotherwise.ifelseuses this logical vector to apply the correct prefix to each value in one go.paste0is a shorthand forpaste(..., sep = ""), making the code cleaner.
This will give you exactly the result you want: values in MyVector get the L_N prefix, others get L_.
内容的提问来源于stack exchange,提问作者Saalva

