How to use the spread function properly in tidyr

前端 未结 2 1073
死守一世寂寞
死守一世寂寞 2020-12-10 17:01

How do I change the following table from:

Type    Name    Answer     n
TypeA   Apple   Yes        5
TypeA   Apple   No        10
TypeA   Apple   DK         8         


        
2条回答
  •  误落风尘
    2020-12-10 17:50

    I think only tidyr is needed to get from df_1 to df_2.

    library(magrittr)
    df_1 <- read.csv(text="Type,Name,Answer,n\nTypeA,Apple,Yes,5\nTypeA,Apple,No,10\nTypeA,Apple,DK,8\nTypeA,Apple,NA,20\nTypeA,Orange,Yes,6\nTypeA,Orange,No,11\nTypeA,Orange,DK,8\nTypeA,Orange,NA,23", stringsAsFactors=F)
    
    df_2 <- df_1 %>% 
      tidyr::spread(key=Answer, value=n)
    

    Output:

       Type   Name DK No Yes NA
    1 TypeA  Apple  8 10   5 20
    2 TypeA Orange  8 11   6 23
    

提交回复
热议问题