Programing

문자열을 변수 이름으로 변환

lottogame 2020. 9. 8. 21:51
반응형

문자열을 변수 이름으로 변환


R을 사용하여 다음 형식의 문자열 목록을 구문 분석합니다.

original_string <- "variable_name=variable_value"

먼저 원래 문자열에서 변수 이름과 값을 추출하고 값을 숫자 클래스로 변환합니다.

parameter_value <- as.numeric("variable_value")
parameter_name <- "variable_name"

그런 다음 parameter_name 문자열과 같은 이름의 변수에 값을 할당하고 싶습니다.

variable_name <- parameter_value

이를 수행하는 기능은 무엇입니까?


할당은 당신이 찾고있는 것입니다.

assign("x", 5)

x
[1] 5

그러나 구매자는 조심하십시오.

R FAQ 7.21 http://cran.r-project.org/doc/FAQ/R-FAQ.html#How-can-I-turn-a-string-into-a-variable_003f 참조


do.call을 사용할 수 있습니다.

 do.call("<-",list(parameter_name, parameter_value))

또 다른 간단한 해결책이 있습니다. http://www.r-bloggers.com/converting-a-string-to-a-variable-name-on-the-fly-and-vice-versa-in-r/

문자열을 변수로 변환하려면 :

x <- 42
eval(parse(text = "x"))
[1] 42

그리고 그 반대 :

x <- 42
deparse(substitute(x))
[1] "x"

x = as.name ( "string")을 사용하고 x를 사용하여 이름 문자열이있는 변수를 참조 할 수 있습니다.

귀하의 질문에 올바르게 대답하는지 모르겠습니다.


찾고있는 기능은 get()다음과 같습니다.

assign ("abc",5)
get("abc")

메모리 주소가 동일한 지 확인 :

getabc <- get("abc")
pryr::address(abc) == pryr::address(getabc)
# [1] TRUE

참조 : R FAQ 7.21 문자열을 변수로 바꾸려면 어떻게해야합니까?


strsplit입력을 구문 분석하고 Greg가 언급했듯이 assign변수를 할당합니다.

original_string <- c("x=123", "y=456")
pairs <- strsplit(original_string, "=")
lapply(pairs, function(x) assign(x[1], as.numeric(x[2]), envir = globalenv()))
ls()

assign좋지만 자동화 스크립트에서 만든 변수를 다시 참조하는 기능을 찾지 못했습니다. ( as.name반대 방식으로 작동하는 것 같습니다). 더 경험이 많은 코더는 의심 할 여지없이 더 나은 솔루션을 가질 수 있지만이 솔루션은 작동하며 R이 자체적으로 실행할 코드를 작성하게된다는 점에서 약간 유머러스합니다.

Say I have just assigned value 5 to x (var.name <- "x"; assign(var.name, 5)) and I want to change the value to 6. If I am writing a script and don't know in advance what the variable name (var.name) will be (which seems to be the point of the assign function), I can't simply put x <- 6 because var.name might have been "y". So I do:

var.name <- "x"
#some other code...
assign(var.name, 5)
#some more code...

#write a script file (1 line in this case) that works with whatever variable name
write(paste0(var.name, " <- 6"), "tmp.R")
#source that script file
source("tmp.R")
#remove the script file for tidiness
file.remove("tmp.R")

x will be changed to 6, and if the variable name was anything other than "x", that variable will similarly have been changed to 6.


I was working with this a few days ago, and noticed that sometimes you will need to use the get() function to print the results of your variable. ie :

varnames = c('jan', 'feb', 'march')
file_names = list_files('path to multiple csv files saved on drive')
assign(varnames[1], read.csv(file_names[1]) # This will assign the variable

From there, if you try to print the variable varnames[1], it returns 'jan'. To work around this, you need to do print(get(varnames[1]))


If you want to convert string to variable inside body of function, but you want to have variable global:

test <- function() {
do.call("<<-",list("vartest","xxx"))
}
test()
vartest

[1] "xxx"

Maybe I didn't understand your problem right, because of the simplicity of your example. To my understanding, you have a series of instructions stored in character vectors, and those instructions are very close to being properly formatted, except that you'd like to cast the right member to numeric.

If my understanding is right, I would like to propose a slightly different approach, that does not rely on splitting your original string, but directly evaluates your instruction (with a little improvement).

original_string <- "variable_name=\"10\"" # Your original instruction, but with an actual numeric on the right, stored as character.
library(magrittr) # Or library(tidyverse), but it seems a bit overkilled if the point is just to import pipe-stream operator
eval(parse(text=paste(eval(original_string), "%>% as.numeric")))
print(variable_name)
#[1] 10

Basically, what we are doing is that we 'improve' your instruction variable_name="10" so that it becomes variable_name="10" %>% as.numeric, which is an equivalent of variable_name=as.numeric("10") with magrittr pipe-stream syntax. Then we evaluate this expression within current environment.

Hope that helps someone who'd wander around here 8 years later ;-)

참고URL : https://stackoverflow.com/questions/6034655/convert-string-to-a-variable-name

반응형