You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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 to sonority_grouped.
  • The TRUE ~ "other" line ensures you don't get NA values for any entries in pre_schwa that aren't in your four vectors. You can remove this line if you prefer NA for 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_lookup acts like a dictionary: when you index it with pre_schwa, it pulls the matching group name for each value.
  • replace_na() handles any unmatched values, turning them into "other" instead of leaving them as NA.

Just remember to replace your_data with the actual name of your DataFrame, and you should be good to go!

内容的提问来源于stack exchange,提问作者phnlg

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 06:31:05