Nathan Peng Li
Nathan Peng Li

Reputation: 15

Add additional rows to data.table in R with values for only some columns

Basically, I have a data.table with a mix of dates, sfc, string, and numerical data and I would like to add additional rows where only three of the columns have data and I would like the rest to be empty. So I am asking how to add empty rows to my data.table before swapping the values using dt[x:y, A=c(...)] etc. Or is there a better way?

Here's an example of my data:

#Required packages
require(data.table)
require(sf)

#Data
ID<-c(1:3)
lon<-c(-86.9655633, -85.8316318, -85.8316318)
lat<-c(34.5967589, 33.6598257, 33.6598257)
Country<-c("Malaysia", "Malayisia", "Singapore")
City<-c("Penang", "Malacca", "Singapore")
area_km2<-c(1048, 277, 728)
event_start<-as.Date(c("2000-01-31", "2000-09-21", "2001-03-17"))
event_end<-as.Date(c("2000-02-14", "2000-10-12", "2001-05-27"))

samp<-data.table(ID, lon, lat, Country, City, area_km2, event_start, event_end)
samp <- st_as_sf(samp, coords = c("lon", "lat"), na.fail=F)

What I want is essentially to add more rows of data with country, city, and area, but leaving everything else empty

add_Country<-c("Indonesia", "Indonesia", "Myanmar")
add_City<-c("Solo", "Jakarta", "Yangon")
add_area_km2<-c(44, 662, 576)
add<-data.table(add_Country, add_City, add_area_km2)

Here is what I've tried so far in appending the values directly and trying to add empty rows


require(tibble)

samp %>% add_row(Country = as.vector(add$add_Country), 
                        City = as.vector(add$add_City), 
                        area_km2= as.vector(add$add_area_km2))
empty=matrix(c(rep.int(NA,length(samp))),nrow=nrow(add),ncol=length(samp))  
colnames(empty) = colnames(samp)  
rbind(samp, empty)

It's my first time posting, so do let me know how I can be clearer. Thanks!

Upvotes: 1

Views: 717

Answers (1)

Peace Wang
Peace Wang

Reputation: 2419

Just to bind the two data.table directly with rbindlist function.

Firstly, you need to construct the added part with the same column names of samp

samp<-data.table(ID, lon, lat, Country, City, area_km2, event_start, event_end)

Country<-c("Indonesia", "Indonesia", "Myanmar")
City<-c("Solo", "Jakarta", "Yangon")
area_km2<-c(44, 662, 576)
add<-data.table(Country, City, area_km2)

Then to bind them together, noticing the option fill = TRUE,

rbindlist(list(samp,add),fill = TRUE)

Upvotes: 1

Related Questions