I have a date
vector containing several names with corresponding dates. For example:
lastUpdate <- as.Date(c(RMO = 18659, NKLA = 18659, JD = 18659, AAPL = 18901,
IBM = 18901, SPCE = 18659, MRNA = 18901, MPNGF = 18659),
origin = "1970-01-01")
However, I would like to separate lastUpdate
into its corresponding names vector (i.e., character
class) and dates vector (i.e., Date
class). Manually it would for example be:
Manually extracting is possible, but tedious (especially if the list is longer):
lastUpdateSymbols <- c("RMO", "NKLA", "JD", "AAPL", "IBM", "SPCE", "MRNA", "MPNGF")
lastUpdateDates <- as.Date(c(18659, 18659, 18659, 18901, 18901, 18659, 18901,
18659), origin = "1970-01-01")
My question:
- With (preferably) only the
System Libraries
, what code could automatically separatelastUpdate
intolastUpdateSymbols
containing only the names (i.e.,character
class) andlastUpdateDates
containing only the dates (i.e.,Date
class) whilst respecting the order/correspondence of the content of objectlastUpdate
?
Thanks in advance.
Systems used:
- R version: 4.1.1 (2021-08-10)
- RStudio version: 1.4.1717
- OS: macOS Catalina version 10.15.7 and macOS Big Sur version 11.6
CodePudding user response:
1) Use enframe
after which frame$name
and frame$value
give the two parts or use it with with(frame, ...)
where ...
is any expression that uses name
and/or value
.
library(tibble)
frame <- enframe(lastUpdate); frame
giving:
# A tibble: 8 x 2
name value
<chr> <date>
1 RMO 2021-02-01
2 NKLA 2021-02-01
3 JD 2021-02-01
4 AAPL 2021-10-01
5 IBM 2021-10-01
6 SPCE 2021-02-01
7 MRNA 2021-10-01
8 MPNGF 2021-02-01
2) or extract each into a variable (no packages):
Names <- names(lastUpdate)
Values <- unname(lastUpdate)
CodePudding user response:
lastUpdate.df <- as.data.frame(lastUpdate)
lastUpdateSymbols <- rownames(lastUpdate.df)
lastUpdateDates <- lastUpdate.df$lastUpdate