convert string back into object in r
I'm assuming you used base::dput()
according to the following example (based on this answer):
# Generate some model over some data
data <- sample(1:100, 30)
df <- data.frame(x = data, y = 2 * data + 20)
model <- lm(y ~ x, df)
# Assuming this is what you did you have the model structure inside model.R
dput(model, control = c("quoteExpressions", "showAttributes"), file = "model.R")
# ----- This is where you are, I presume -----
# So you can copy the content of model.R here (attention to the single quotes)
mstr <- '...'
# Execute the content of mstr as a piece of code (loading the model)
model1 <- eval(parse(text = mstr))
# Parse the formulas
model1$terms <- terms.formula(model1$terms)
# ----- Test it -----
# New data
df1 <- data.frame(x = 101:110)
pred <- as.integer(predict(model, df1))
pred1 <- as.integer(predict(model1, df1))
identical(pred, pred1)
# [1] TRUE
model
#
# Call:
# lm(formula = y ~ x, data = df)
#
# Coefficients:
# (Intercept) x
# 20 2
#
model1
#
# Call:
# lm(formula = y ~ x, data = df)
#
# Coefficients:
# (Intercept) x
# 20 2
# Check summary too (you'll see some minor differences)
# summary(model)
# summary(model1)
How to convert a string in a function into an object?
The trick is to use parse
. For instance:
> x <- "A"
> eval(parse(text=paste("df$", x, sep = "")))
[1] 1 2 3 4 5 6 7 8 9 10
See also this Q/A: Evaluate expression given as a string
Convert string to datatime object in r
As previous comments and answers suggested, the POSIXct
(i.e., datetime) class in R
always stores dates along with times. If you convert from a character object with just times to that class, today's date is added by default (if you want another date, you could do, for example, this: as.POSIXct(paste("2020-01-01", times), format = "%Y-%m-%d %H:%M")
).
However, this should almost never be a problem since you can use format(times, format = "%H:%M")
or for ggplot2
scale_x_datetime
to get just the times back. For plotting, this would look something like this:
times <- c("00:30", "01:30", "02:30", "03:30", "04:30", "05:30", "06:30", "07:30", "08:30", "09:30", "10:30", "11:30", "12:30", "13:30", "14:30",
"15:30", "16:30", "17:30", "18:30", "19:30", "20:30", "21:30", "22:30", "23:30")
library(tidyverse)
df <- tibble(
time_chr = times,
time = as.POSIXct(times, format = "%H:%M"),
value = rnorm(length(times))
)
df
#> # A tibble: 24 x 3
#> time_chr time value
#> <chr> <dttm> <dbl>
#> 1 00:30 2020-03-12 00:30:00 0.352
#> 2 01:30 2020-03-12 01:30:00 -0.547
#> 3 02:30 2020-03-12 02:30:00 -0.574
#> 4 03:30 2020-03-12 03:30:00 0.843
#> 5 04:30 2020-03-12 04:30:00 0.798
#> 6 05:30 2020-03-12 05:30:00 -0.620
#> 7 06:30 2020-03-12 06:30:00 0.213
#> 8 07:30 2020-03-12 07:30:00 1.21
#> 9 08:30 2020-03-12 08:30:00 0.370
#> 10 09:30 2020-03-12 09:30:00 0.497
#> # … with 14 more rows
ggplot(df, aes(x = time, y = value)) +
geom_line() +
scale_x_datetime(date_labels = "%H:%M")
Created on 2020-03-12 by the reprex package (v0.3.0)
Convert JSON string to JSON object using R
I find myself doing
toJSON(fromJSON(jsonStr))
every time I want to pass a JSON string just to change it's class to json.
The idiomatic way to change the class of an object is:
class(jsonStr) <- "json"
To make sure the string is valid, might want to use jsonlite::validate(jsonStr)
after assigning the class.(Thanks to @SybolixAU for pointing this out.)
Convert string to a variable name
assign is what you are looking for.
assign("x", 5)
x
[1] 5
but buyer beware.
See R FAQ 7.21
http://cran.r-project.org/doc/FAQ/R-FAQ.html#How-can-I-turn-a-string-into-a-variable_003f
Convert any R variable's value to string
Try capture.output
. It's essentially your rawString
, but built in.
capture.output(myFunc)
[1] "function(x) { x + 1}"
Unfortunately I can't speak for sparkTable
as I don't have it.
You might also consider ?dput
, which is a good way to provide something for users to copy-paste into their consoles to recreate your variable, though doesn't convert to string (e.g. dput(iris)
--> if I were to copy-paste this into my terminal I'd get exactly what you got).
Related Topics
Is R Superstitious Regarding Posixct Data Type
What Techniques Exists in R to Visualize a "Distance Matrix"
How to Check Existence of an Input Argument for R Functions
Difference Between As.Data.Frame(X) and Data.Frame(X)
Formatting Ggplot2 Axis Labels with Commas (And K? Mm) If I Already Have a Y-Scale
Producing Subscripts in R Markdown
An Elegant Way to Change Columns Type in Dataframe in R
R Text Mining Documents from CSV File (One Row Per Doc)
Dplyr::First() to Choose First Non Na Value
R: How to Get the Last Element from Each Group
Screening (Multi)Collinearity in a Regression Model
Avoid Rbind()/Cbind() Conversion from Numeric to Factor
Automating Version Increase of R Packages
How to Rename a Variable in R Without Copying the Object
Is There Any Other Package Other Than "Sentiment" to Do Sentiment Analysis in R
Ggplot2: Multiple Plots with Different Variables in a Single Row, Single Grouping Legend