How to load data from one data frame to other in R?

89 views Asked by At

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.

1

There are 1 answers

1
jpsmith On

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