R语言tidyverse:基于pre_schwa列生成sonority_grouped列求助
Solution for Adding Sonority Groups in Tidyverse
Hey there! Let's get this sorted out. Since you're working with the tidyverse, the right tool for this job is case_when() inside mutate()—filter() isn't what you need here because it removes rows, and we just want to add a new column based on existing values.
Method 1: Using case_when() (Most Readable for Beginners)
This approach is straightforward and easy to tweak if you need to adjust your groups later:
library(tidyverse) # Your existing group vectors vowels <- c("AY1", "ER0", "IY0", "IY1", "UW2") sonorants <- c("M","N", "R", "Y", "ZH", "W") fricatives <- c("F", "S", "SH", "TH", "V", "Z") stops <- c("B", "CH", "D", "G", "JH", "K", "P", "T") # Replace "your_data" with the name of your actual DataFrame your_data <- your_data %>% mutate(sonority_grouped = case_when( # Check if pre_schwa is in each group vector, assign the group name pre_schwa %in% vowels ~ "vowels", pre_schwa %in% sonorants ~ "sonorants", pre_schwa %in% fricatives ~ "fricatives", pre_schwa %in% stops ~ "stops", # Catch any values that don't match the four groups (optional but helpful) TRUE ~ "other" ))
How this works:
case_when()evaluates each condition in order. As soon as a condition is true for a row, it assigns the corresponding value tosonority_grouped.- The
TRUE ~ "other"line ensures you don't getNAvalues for any entries inpre_schwathat aren't in your four vectors. You can remove this line if you preferNAfor unmatched values.
Method 2: Using a Lookup Vector (Great for Scalable Groups)
If you might expand your groups later, creating a named lookup vector keeps your code clean:
# Create a named vector where each sound maps to its group group_lookup <- c( # Assign "vowels" to every entry in the vowels vector setNames(rep("vowels", length(vowels)), vowels), setNames(rep("sonorants", length(sonorants)), sonorants), setNames(rep("fricatives", length(fricatives)), fricatives), setNames(rep("stops", length(stops)), stops) ) # Add the grouped column, replacing NA with "other" if needed your_data <- your_data %>% mutate(sonority_grouped = replace_na(group_lookup[pre_schwa], "other"))
How this works:
group_lookupacts like a dictionary: when you index it withpre_schwa, it pulls the matching group name for each value.replace_na()handles any unmatched values, turning them into "other" instead of leaving them asNA.
Just remember to replace your_data with the actual name of your DataFrame, and you should be good to go!
内容的提问来源于stack exchange,提问作者phnlg
相关产品推荐
相关产品推荐

