转置特定列

Jim*_* O. 1 transpose r

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

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" 
Run Code Online (Sandbox Code Playgroud)

我希望它看起来像这样:

     country sharp suicide others
[1,] "US"    "30"  "20"    "50"  
[2,] "Korea" "40"  "40"    "20"  
Run Code Online (Sandbox Code Playgroud)

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

joh*_*ane 5

如果您转换为数据帧,您可以使用spreadfromtidyr

library(tidyr)
numbers_df <- as.data.frame(numbers,stringsAsFactors=FALSE)
numbers_transpose <- numbers_df %>% spread(key = cause, value = value)
Run Code Online (Sandbox Code Playgroud)