如何将非规范化数据转换为规范化数据,反之亦然或在R中转置

时间:2015-03-10 02:47:12

标签: r

我的数据格式如下:

Japan_n US_n Canada_n Japan_mean US_mean Canada_mean Japan_cv US_cv Canada_cv
76      55     89       145.49    163.78    122.18     23.12   25.47   13.85

我想在R:

中使用以下格式输出
        n    mean     cv
Japan  76    145.99   23.12
US     55    163.78   25.47
Canada 89    122.18   13.85

我该怎么做?

1 个答案:

答案 0 :(得分:0)

试试这个

library(dplyr)
library(tidyr)

data <- structure(list(Japan_n = 76L, 
                       US_n = 55L, 
                       Canada_n = 89L, 
                       Japan_mean = 145.49, 
                       US_mean = 163.78, 
                       Canada_mean = 122.18, 
                       Japan_cv = 23.12, 
                       US_cv = 25.47, 
                       Canada_cv = 13.85), 
                  .Names = c("Japan_n", "US_n",
                             "Canada_n", "Japan_mean", 
                             "US_mean", "Canada_mean", 
                             "Japan_cv", "US_cv", "Canada_cv"), 
                  class = "data.frame", 
                  row.names = c(NA, -1L))

my_solution <-
    gather(data, col_01, col_02) %>% 
    separate(., col_01, into = c("geo", "stat")) %>% 
    spread(., stat, col_02)

my_solution

     geo    cv   mean  n
1 Canada 13.85 122.18 89
2  Japan 23.12 145.49 76
3     US 25.47 163.78 55