R语言:基于字符串末尾字符的条件赋值及数据合并咨询
Got it, let's walk through how to add that conditional column you need. Since you've already split the Product column and merged the data into final, we just need to focus on checking the last character of the original Product strings and assigning the right value.
Step 1: Grab the last character of each Product string
You can do this with either base R or the stringr package (which you're already using for str_split, so it's a consistent choice):
- With base R: Use
substr()andnchar()to target the final character:last_char <- substr(sains_part$Product, nchar(sains_part$Product), nchar(sains_part$Product)) - With
stringr(cleaner syntax): The-1instr_sub()tells it to start from the last character:library(stringr) last_char <- str_sub(sains_part$Product, -1)
Step 2: Add the conditional column to your merged data
Use ifelse() to create the new column (let's call it multiplier for clarity) where we assign 1.03 if the last character is 'L', otherwise 1. You can directly add this to your final data frame:
Base R version:
final$multiplier <- ifelse(last_char == "L", 1.03, 1)
One-liner with stringr:
Skip storing last_char and do it all in one step:
final$multiplier <- ifelse(str_sub(sains_part$Product, -1) == "L", 1.03, 1)
Bonus: Handle case sensitivity
If there's a chance some entries end with lowercase 'l', make the check case-insensitive with tolower():
final$multiplier <- ifelse(tolower(str_sub(sains_part$Product, -1)) == "l", 1.03, 1)
A quick note: We don't need to use the split extra columns here because we're checking the original full Product string—no need to involve the split parts unless you had a different requirement!
内容的提问来源于stack exchange,提问作者Matthew Appleyard

