I have a dataframe df like this
> df <- data.frame(type=c("Id","v1","v2","Id","v1","v1","v2","Id","v1","v2","v3"),num=c(1000,200,500,1001,727,50,800,1002,400,365,865))
> df
type num
1 Id 1000
2 v1 200
3 v2 500
4 Id 1001
5 v1 727
6 v1 50
7 v2 800
8 Id 1002
9 v1 400
10 v2 365
11 v3 865
I need to create another data frame with Id, v1, v2, v3 as the column names and corresponding values from df such that the variable below each id belong to that id and when the same variable repeats it has to be mapped with the same id and if the variable is not present NA has to be given. This is the desired output.
Id v1 v2 v3
1 1000 200 500 NA
2 1001 727 NA NA
3 1001 50 800 NA
4 1002 400 365 865
I have thought about a method using for loop. But it seems complicated and difficult to structure it. Is there a way without using for loops.
try to do it this way
library(tidyverse)
df %>%
mutate(id = ifelse(type == "Id", num, NA)) %>%
fill(id) %>%
filter(type != "Id") %>%
group_by(id, type) %>%
mutate(n = row_number()) %>%
pivot_wider(c(id, n), names_from = type, values_from = num) %>%
select(-n) %>%
ungroup()
# A tibble: 4 x 4
id v1 v2 v3
<dbl> <dbl> <dbl> <dbl>
1 1000 200 500 NA
2 1001 727 800 NA
3 1001 50 NA NA
4 1002 400 365 865
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.