转置特定列

时间:2017-09-20 16:12:21

标签: r transpose

我正在使用的实际数据更长,并且有更多变量,但我有一个看起来像这样的数据:

country <- c("US", "US", "US", "Korea", "Korea", "Korea")
cause <- c("sharp", "suicide", "others")
value <- c(30, 20, 50, 40, 40, 20)
numbers <- cbind(country, cause, value)

     country cause     value
[1,] "US"    "sharp"   "30" 
[2,] "US"    "suicide" "20" 
[3,] "US"    "others"  "50" 
[4,] "Korea" "sharp"   "40" 
[5,] "Korea" "suicide" "40" 
[6,] "Korea" "others"  "20" 

我希望它看起来像这样:

     country sharp suicide others
[1,] "US"    "30"  "20"    "50"  
[2,] "Korea" "40"  "40"    "20"  

我已尝试过转置命令,但R会转置列中的所有内容,并且国家/地区的名称会重复多次。如何将原因作为列名移动并在其下面分配适当的值?

1 个答案:

答案 0 :(得分:2)

如果您转换为数据框,则可以使用spread

中的tidyr
library(tidyr)
numbers_df <- as.data.frame(numbers,stringsAsFactors=FALSE)
numbers_transpose <- numbers_df %>% spread(key = cause, value = value)