[R] Convert a character string to variable names

Rui Barradas ru|pb@rr@d@@ @end|ng |rom @@po@pt
Tue Feb 8 00:32:42 CET 2022


Hello,

If you want to avoid eval(parse(.)), here is another solution.

First split the strings by '$' giving the data set name in the 1st 
element of each list member and the column name in the 2nd. With a 
sapply loop find the data set name then ?get the data itself in df1. 
Finally, another sapply loop creates a vector of column names. And it's 
a matter of extracting those columns with standard '[' (or '[['.


.x <- scan(text = '"mtcars$disp" "mtcars$hp"   "mtcars$cyl"', what = 
character())

s <- strsplit(.x, "\\$")
df1 <- unique(sapply(s, `[`, 1))
df1 <- get(df1, envir = .GlobalEnv)
cols <- sapply(s, `[`, 2)

# all columns, result is a data.frame
head(df1[cols])
#>                   disp  hp cyl
#> Mazda RX4          160 110   6
#> Mazda RX4 Wag      160 110   6
#> Datsun 710         108  93   4
#> Hornet 4 Drive     258 110   6
#> Hornet Sportabout  360 175   8
#> Valiant            225 105   6

# first column in 'cols', result is a data.frame
head(df1[ cols[1] ])
#>                   disp
#> Mazda RX4          160
#> Mazda RX4 Wag      160
#> Datsun 710         108
#> Hornet 4 Drive     258
#> Hornet Sportabout  360
#> Valiant            225

# second column in 'cols', result is a vector
head(df1[[ cols[2] ]])
#> [1] 110 110  93 110 175 105


Hope this helps,

Rui Barradas

Às 22:55 de 07/02/2022, Erin Hodgess escreveu:
> Hello!
> 
> I have a character string that is a vector of variable names.  I would like
> to use those names to access the variables and create a matrix.
> I tried the following:
> 
>> .x
> 
> [1] "mtcars$disp" "mtcars$hp"   "mtcars$cyl"
> 
>> .y <- NULL
> 
>> for(i in 1:3) {
> 
> + .y[i] <- c(as.name(.x[[i]]))
> 
> + }
> 
>> .y
> 
> [[1]]
> 
> `mtcars$disp`
> 
> 
> [[2]]
> 
> `mtcars$hp`
> 
> 
> [[3]]
> 
> `mtcars$cyl`
> 
> 
> But I am having trouble converting the variables in .y into a matrix.
> 
> 
> I tried all kinds of stuff with bquote, deparse, do.call, but no good.
> 
> 
> I have a feeling that it's something simple, and I'm just not seeing it.
> 
> 
> Thanks,
> 
> Erin
> 
> 
> 
> 
> Erin Hodgess, PhD
> mailto: erinm.hodgess using gmail.com
> 
> 	[[alternative HTML version deleted]]
> 
> ______________________________________________
> 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.



More information about the R-help mailing list