Reputation: 1480
I have an object name
Test12<-c(8,7,4,3,5,67,3,9,6,6,56,742,23,12,45,56)
I would like to extract the last two numbers from the objects name or from Test12 to obtain the numbers 1 and 2 separatedly and place them into two objects.
a<- 1
b<- 2
I have tried with
x <- name(Test12)
substrRight <- function(x, n){
substr(x, nchar(x)-n+1, nchar(x))
}
substrRight(x, 2)
[1] "8" "7" "4" "3" "5" "67" "3" "9" "6" "6" "56" "42" "23" "12" "45" "56"
However I get the last 2 ítems of each of the objects elements.
Any help welcomed
Upvotes: 2
Views: 188
Reputation: 887891
You may also try
library(stringr)
list2env(setNames(
as.list(str_extract_all(deparse(substitute(Test12)),
perl("\\d(?=\\b$)|\\d(?=[0-9]$)"))[[1]]),
letters[1:2]),
envir=.GlobalEnv)
a
#[1] "1"
b
#[1] "2"
deparse(substitute(Test12)) #gets the name of the object
#[1] "Test12"
Regex "\\d(?=\\b$)
match a digit lookahead
for word boundary at the end of string |
or \\d(?=[0-9]$)")
a digit and lookahead
for another digit at the end of string.
Suppose your string is:
T95es34t12 <- 1:5
str_extract_all(deparse(substitute(T95es34t12)), perl("\\d(?=\\b$)|\\d(?=[0-9]$)"))[[1]]
#[1] "1" "2"
as.list
creates a list,then name the elements of list with a
, b
using setNames
and use list2env
to assign the name of the list elements to the list values.
Upvotes: 1
Reputation: 984
You can use this:
substrRight <- function(x, n){
substr(x, nchar(x)-n+1, nchar(x))
}
var.name <- deparse(substitute(test12))
var.nums <- substrRight(var.name, 2)
var.nums <- strsplit(var.nums, "")
var.nums <- unlist(var.nums)
var.nums <- as.vector(as.numeric(var.nums))
Upvotes: 1
Reputation: 17621
nm <- bquote(Test12)
or
nm <- quote(Test12)
or
nm <- "Test12"
or
nm <- deparse(substitute(Test12))
as per answer of @Al.Sal
Will work, then:
a <- substr(nm, nchar(nm)-1, nchar(nm)-1)
b <- substr(nm, nchar(nm), nchar(nm))
> a
[1] "1"
> b
[1] "2"
Upvotes: 1