【问题标题】:Combining mutate and filter functions结合变异和过滤功能
【发布时间】:2018-10-29 02:18:56
【问题描述】:

我是 R 语言的初学者,如果我使用 tidyverse 包复制问题,很抱歉。

我的问题如下: 我有一个数据框,其中一列看起来像这样

pre_schwa
IY0
SH
Z
+1500 rows

现在我需要创建一个与该特定列相对应的列(变量)。我创建了四个向量:

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")

有了这个,我想创建一个名为 sonority_grouped 的列,它由四个名称(元音、响音、摩擦音、塞音)组成,具体取决于 pre_schwa 列中的字符,所以我希望它看起来像这样

  pre_schwa              sonority_grouped
  SH                     fricatives
  ER0                    vowels
  B                      stops
  Z                      fricative
  +1500 rows

我尝试通过 %>% 组合 mutate()filter() 函数,但我编程很烂。 感谢您的回复。

【问题讨论】:

    标签: r variables filter dplyr


    【解决方案1】:

    数据

    df <- read.table(text="pre_schwa
    IY0
    SH
    Z", header=TRUE, stringsAsFactors=FALSE)
    

    我建议通过

    将您的单个向量转换为 data.frame
    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")
    
    patterns <- c("vowels", "sonorants", "fricatives", "stops")
    df2 <- stack(mget(patterns))
    

    或者,正如 MrFlick 所指出的,您可以使用lattice::make.groups(...)

    df2 <- lattice::make.groups(vowels, sonorants, fricatives, stops) %>% 
              dplyr::rename(pre_schwa=data, sonority_grouped=which)    
    

    那么你可以使用dplyr::left_join来获取你的结果

    ans <- dplyr::left_join(df, df2, by=c("pre_schwa" = "values"))
      # pre_schwa        ind
    # 1       IY0     vowels
    # 2        SH fricatives
    # 3         Z fricatives
    

    使用 MrFlick 的回答使用

    ans <- dplyr::left_join(df, df2)
    

    【讨论】:

    • 这是将df2 用作查找表df2 &lt;- lattice::make.groups(vowels, sonorants, fricatives, stops) %&gt;% rename(pre_schwa=data, sonority_grouped=which) 的另一种方法
    • 了解有用的功能 - 谢谢 - 和更新的答案
    【解决方案2】:

    您也可以使用case_when

    df %>%
      mutate(sonority_grouped = case_when(
        pre_schwa %in% vowels ~ "vowels",
        pre_schwa %in% sonorants ~ "sonorants",
        pre_schwa %in% fricatives ~ "fricatives",
        pre_schwa %in% stops ~ "stops",
      ))
    

    【讨论】:

      猜你喜欢
      • 2019-06-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-05-15
      • 2012-02-26
      • 1970-01-01
      • 1970-01-01
      • 2019-07-20
      相关资源
      最近更新 更多