z <- c("1001","1001","1002","1002")
h <- c("Yes","No","Yes","No")
count <- c("300","200","500","100")
df = data.frame(z,h,count)
df
z h count
1 1001 Yes 300
2 1001 No 200
3 1002 Yes 500
4 1002 No 100
Here I have two values in the "z" column that are repeated, but with different values in "h" and "count". I want to create two new columns called "h2" and "count2" that has the unique values for each unique id in "z". Here is the expected result. How would I write this in code?
z h count h2 count2
1 1001 Yes 300 No 200
2 1002 Yes 500 No 100
CodePudding user response:
I believe you are looking for pivot_wider()
function
df %>%
pivot_wider(names_from = c(h),values_from = c(h,count)) %>%
rename(z=z,h=h_Yes,h2=h_No,count=count_Yes,count2=count_No)