代码之家  ›  专栏  ›  技术社区  ›  Simon Harmel

通过将两组变量粘贴到R中的一组变量中,实现宽格式数据

  •  2
  • Simon Harmel  · 技术社区  · 2 年前

    我试着把我的 DATA 进入我的 Desired_output 使用:

    pivot_wider(DATA, names_from = Year, values_from = c(Type, Language))

    没有成功。有没有办法实现我的 所需输出 ?

    library(tidyverse)
    
    DATA <- read.table(header=TRUE, text="
    ID District       Type Year Language
    1 GreshamBarlow   5F  1617   Spanish
    1 GreshamBarlow   5F  1718   Spanish
    2 JeffersonCounty 5F  1617   English
    2 JeffersonCounty 5F  1718   English")
    
    
    Desired_output <- read.table(header=TRUE, text="
    ID District        1617             1718 
    1  GreshamBarlow   5F_Spanish       5F_Spanish
    2  JeffersonCounty 5F_English       5F_English")
    
    2 回复  |  直到 2 年前
        1
  •  3
  •   Onyambu    2 年前
    DATA %>% 
       unite(Type, Type, Language) %>% 
       pivot_wider(names_from = Year, values_from = Type)
    
    # A tibble: 2 × 4
         ID District        `1617`     `1718`    
      <int> <chr>           <chr>      <chr>     
    1     1 GreshamBarlow   5F_Spanish 5F_Spanish
    2     2 JeffersonCounty 5F_English 5F_English
    
        2
  •  0
  •   shaun_m    2 年前

    您可以在执行之前创建组合变量 pivot_wider() 它应该会给出你所要求的结果

    Desired_output <- DATA %>%
        transmute(ID, District, Year, newvar = paste(Type, Language, sep="_")) %>%
        pivot_wider(names_from = Year, values_from = newvar)
    
    Desired_output
    #   ID        District     `1617`     `1718`
    # 1  1   GreshamBarlow 5F_Spanish 5F_Spanish
    # 2  2 JeffersonCounty 5F_English 5F_English
    
    推荐文章