1

The actual data I am working with is longer and has more variables, but I have a data that looks something like this:

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" 

I want it to look like this:

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

I've tried the transpose command, but R transposes everything in the column and the names of countries repeat multiple times. How can I move the causes as column names and assign their appropriate values underneath it?

Jim O.
  • 1,091
  • 12
  • 31

1 Answers1

5

If you convert to a dataframe you can use spread from tidyr

library(tidyr)
numbers_df <- as.data.frame(numbers,stringsAsFactors=FALSE)
numbers_transpose <- numbers_df %>% spread(key = cause, value = value)
Jim O.
  • 1,091
  • 12
  • 31
johnckane
  • 645
  • 8
  • 18