读入文件并将字段设置为 R 中的变量

Read in a file and set fields as variables in R

我正在尝试读入文件并让 R 将每个数据对设置为环境变量。

我有一个来自网络的输入文件,其中包含以下数据。它有需要读入的数字变量和字符变量。这就是我挂断电话的地方,因为我似乎只能将它们作为一个或另一个引入,这使得分配或 do.call 出错当它命中归类为数字的字符时,反之亦然。

有什么想法吗?

input file "input":
user <- "johndoe", date <- "1-30-2019", run <- 1, scoring <- "default", 
high_cutoff <- 70, low_cutoff <- 15, bg1 <- 12, bg2 <- 12, bg3 <- 12, 
group_cut <- 60, stbg <- "no", factor <- 25, rest <- 2, 
loo_enable <- "no"

wd <- getwd() 
phpvars <- as.data.frame(t(read.table(paste0(wd, "/input"), sep = ",")))


#attempt 1 - reads everything in as character
for (i in phpvars$V1){
 x<- t(as.data.frame(strsplit(i," <- ")))
 assign(x[1,1],(x[1,2]))
}

#attempt 2 - tries to detect type of each data point as it comes in, and 
#assign as. (numeric or character)

for (i in phpvars$V1){
 x<- t(as.data.frame(strsplit(i," <- ")))
 type <- typeof(x[1,2])
 d <- paste0("as.", type)
 e <- x[1,2]
 assign(x[1,1],paste(d,(e)))
 }



#alternate to assign - has same problems though
do.call("<-",list(x[1,1],x[1,2]))

作为环境变量的期望输出:

 user <- "johndoe"
 date <- "1-30-2019"
 run <- 1
 scoring <- "default"
 high_cutoff <- 70
 low_cutoff <- 15
 bg1 <- 12
 bg2 <- 12
 bg3 <- 12
 group_cut <- 60
 stbg <- "no"
 factor <- 25
 rest <- 2
 loo_enable <- "no"

有没有办法(更好的方法)读入数据并将它们设置为环境变量?

您已经有一个很好的引用输入。通过指定在使用 read.table() 函数时用 quote = "" 参数引用您的输入字符串来利用这一点:

wd <- getwd() 
phpvars <- as.data.frame( t( read.table( paste0(wd, "/input") ,
                                         sep = ",",   
                                         quote = "" ) ) )

然后你只需要解析 phpvars table 的每一行并分别使用 parse()eval() 函数对其进行评估:

 for(i in phpvars$V1){

     eval( parse( text = as.character(i) ) )
 }