[R] Build a data.table via two string lists

Bill Dunlap w||||@mwdun|@p @end|ng |rom gm@||@com
Mon Jun 6 19:08:24 CEST 2022


You could turn your row values in a list, attach names to that list, and
pass the list to data.frame():
> cl <- c("timestamp", "assess", "catheter", "service", "ref")
> rw <- c("1654508112", "3", "gel", "2785",
"16545081121a8d8f956cb871053a3f56b782b70a76")
> df <- data.frame(setNames(as.list(rw), nm=cl))
> df
   timestamp assess catheter service
 ref
1 1654508112      3      gel    2785
16545081121a8d8f956cb871053a3f56b782b70a76

At this point all the columns have type "character".  You may want to
convert some columns to more meaningful types, e.g., "timestamp" to a
date/time class and "assess" to a number.  E.g.,
> df[["timestamp"]] <- as.POSIXct(as.numeric(df[["timestamp"]]),
origin=as.POSIXct("1970/01/01"))
> df[["assess"]] <- as.numeric(df[["assess"]])
> df
            timestamp assess catheter service
         ref
1 2022-06-06 10:35:12      3      gel    2785
16545081121a8d8f956cb871053a3f56b782b70a76
> str(df)
'data.frame':   1 obs. of  5 variables:
 $ timestamp: POSIXct, format: "2022-06-06 10:35:12"
 $ assess   : num 3
 $ catheter : chr "gel"
 $ service  : chr "2785"
 $ ref      : chr "16545081121a8d8f956cb871053a3f56b782b70a76"

-Bill


On Mon, Jun 6, 2022 at 9:51 AM John RF Staples via R-help <
r-help using r-project.org> wrote:

> Hello everyone,
>
> I have the following two structures:
>
> # str(cl)
> # chr [1:5] "timestamp" "assess" "catheter" "service" "ref"
>
> # str(rw)
> # chr [1:5] "1654508112" "3" "gel" "2785"
> “16545081121a8d8f956cb871053a3f56b782b70a76"
>
> From which I would like to generate a 5 col x 1 row data.table; the
> question is ‘how’?
>
> ‘cl’ represents the column names; ‘rw’ the row values.
>
> With anticipatory thanks …
> John
> ______________________________________________
> R-help using r-project.org mailing list -- To UNSUBSCRIBE and more, see
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide
> http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
>

	[[alternative HTML version deleted]]



More information about the R-help mailing list