0

I have a mini data frame

index data district month
1 data1 District-1 month1
2 data2 District-2 month2

and so on

I want to load the data values from the data column to the data frame which has a structure like:-

month1 month2
District-1 data1 NA
District-2 NA data2

and so on

In short, the data1 from the mini data frame should go to its perfect cell in the big data frame where the district and months are matching. All the cells of big data frame are filled with null.

Rubén
  • 34,714
  • 9
  • 70
  • 166
Ram Patil
  • 45
  • 1
  • 8

1 Answers1

1

You don't have District-2 in your original data (though it appears in your desired data), but generally if you wanted this, try using tidyr::pivot_wider():

# Data with district 2 in it
df <- data.frame(index  = rep(1,4),
                 data = c("data1","data2","data3","data4"),
                 district = c("District-1", "District-1", "District-2", "District-2"),
                 month = rep(c("month1","month2"),2))

library(tidyr)
df %>% pivot_wider(names_from = "month", values_from = "data") %>% select(-index)

Output

#  district   month1 month2
#  <chr>      <chr>  <chr> 
#1 District-1 data1  data2 
#2 District-2 data3  data4 
jpsmith
  • 11,023
  • 5
  • 15
  • 36
  • Hi! What I wanted to do is load the data with the appropriate district and month to the bigger data frame. It is just that in a bigger data frame the months are columns. For eg., if a data has district-10 and month-9 in its respective row then I want to put that data in row district-10 and column month-9 – Ram Patil Apr 25 '22 at 04:50