dataframe to table转换像这种格式你能帮帮我吗?

时间:2018-03-30 01:09:49

标签: r

enter image description here

我想左数据转换为右表!! 我的代码是,

Respond<-as.factor(c(1,2,3,4,5,6,7,8,9,10,11,12))

Major<-as.factor(c("AD","B","E","AD","B","AD","B","E","AD",
     "E","AD","E"))

score<-c(2.5,0.5,2,3,2,2,1,1,1,0.5,3,1.5)
data<-data.frame(Respond,Major,score)

输入此代码后,我尝试使用tapply函数,..等等,但我

找不到让桌子像右一样的方法......

请帮帮我!!专家〜!!!

2 个答案:

答案 0 :(得分:1)

以下内容将再现您的预期输出:

library(dplyr);
library(magrittr);
data %>%
    group_by(Major) %>%
    mutate(number = 1:n()) %>%
    select(-Respond) %>%
    spread(Major, score) %>%
    select(number, B, E, AD)
    ## A tibble: 5 x 4
    #  number      B      E    AD
    #   <int>  <dbl>  <dbl> <dbl>
    #1      1  0.500  2.00   2.50
    #2      2  2.00   1.00   3.00
    #3      3  1.00   0.500  2.00
    #4      4 NA      1.50   1.00
    #5      5 NA     NA      3.00

答案 1 :(得分:1)

另一种选择是使用dcast转换为宽格式,然后map_df按照值NA的顺序转换为所有列。

require(tidyverse)
require(reshape2)
data %>% 
    dcast(Respond ~ Major) %>% 
    map_df(~ .[order(is.na(.))])