简体   繁体   中英

filling in a data.table with information from multiple objects in R

Within a large function, I would like to create a "summary table" of sorts. This summary table, summaries information from multiple R objects, that have been created within the function. The objects are:

Data table with the information on the limit

>     str(limit)
Classes ‘data.table’ and 'data.frame':  1 obs. of  3 variables:
 $ id   : num 6292
 $ type : chr "DAILY"
 $ value: chr "350"
 - attr(*, ".internal.selfref")=<externalptr>

vector with position of the element in mydata that is over the limit limits$value

n <- which(mydata$amount > as.double(limit$value))
str(n)
int [1:4960] 1 2 3 5 6 9 11 16 19 20 ...

I have now created an empty data.table problem with rows that I want to use to summarise the elements that are over the limit in mydata :

  problem <- data.table("LIMITid" = character(),
                        "LIMITtype" = character (), 
                        "LIMITvalue" = character (), 
                        "amount" = double(), 
                        "customerID" = character())

Finally, i want to populate my problem data.table with the corresponding information. I tried:

if(length(n) > 0){
 problem$LIMITid <- limit$id
 problem$LIMITtype <- limit$type
 problem$LIMITvalue <- limit$value
 problem$amount <- mydata$amount
 problem$customerID <- mydata$customerID
}

How can i populate the data.table ? I was thinking of using a loop, but i am unsure how to loop over positions in an element - n %in% nrownames(mydata) ?

We can specify the columns of interest in .SDcols and then subset the .SD (Subset of Data.table) with the index provided by 'n' and cbind with the 'limits' dataset

library(data.table)
cbind(limits, mydata[, .SD[n], .SDcols = c("amount", "customerID")])

Wouldn't this work?

library(data.table)
data.table(limits, amount = mydata$amount[n], customerID = mydata$customerID[n])

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM