#I have the given dataframe:
numbers <- c(5,5,5,5,3,3,1,1,1)
outputs <- c('red','blue','blue','purple','red','yellow','red','orange','blue')
data <- data.frame(numbers,outputs)
data
#I want to combine all colors associated with each unique number into a row. My desired output would be:
numbers <- c(5,3,1)
output1 <- c('red','blue','yellow')
output2 <- c('blue','yellow','orange')
output3 <- c('blue','na','blue')
output4 <- c('purple','na','na')
data <- data.frame(numbers,output1,output2,output3,output4)
#What is the best way to do this?
CodePudding user response:
You can use this code:
numbers <- c(5,5,5,5,3,3,1,1,1)
outputs <- c('red','blue','blue','purple','red','yellow','red','orange','blue')
data <- data.frame(numbers,outputs)
data
library(dplyr)
library(tidyr)
library(data.table)
data %>%
mutate(n = rowid(numbers)) %>%
pivot_wider(names_from = n, values_from = outputs, names_prefix = "output")
Output:
# A tibble: 3 × 5
numbers output1 output2 output3 output4
<dbl> <chr> <chr> <chr> <chr>
1 5 red blue blue purple
2 3 red yellow NA NA
3 1 red orange blue NA