R - Я хочу, чтобы имя фрейма данных определялось аргументом командной строки - PullRequest
1 голос
/ 09 марта 2012

Я хочу, чтобы имя фрейма данных определялось аргументом командной строки.Следующее должно прояснить, что я пытался сделать ... Я надеюсь!

Выполнить с помощью:

rterm --vanilla < c:/temp/myprog.txt --args XYZ

Содержимое c: /temp/myprog.txt:

# I am using command line arguments
Args <- commandArgs(TRUE);

# Args[1] is the desired dataframe name
print(Args[1]);

# Create a simple dataframe
df <- c(c(1,2),c(3,4));
print(df);

# Save it
path <- 'c:/temp/mydata.rdata'
save(df, file=path);

# Clear the dataframe from memory
rm(df);

# Is it really gone?
print(df);

# Load the dataframe from disk
load(path);

# Did you get it?
print(df);

# --- This is where things start to go bad ---
# --- I know this is wrong, and I know why ---
# --- but it should make clear what it is  ---
# --- I am attempting to do.               ---

# Copy it to dataframe with name passed from command line
Args[1] <- df;

# Write it to disk with the new name
save(Args[1], file=path);

# Clear the dataframe from memory
rm(Args[1]);

# Is it really gone?
print(Args[1]);

# Load the dataframe from disk
load(path);

# Did you get it?
print(Args[1]);

# That's all

Заранее спасибо.

** ДОБАВЛЕНО ПОСЛЕ ФАКТА ... ЭТО РАБОТАЕТ ...

C:\Program Files\R\R-2.14.2\bin\x64>rterm --vanilla < c:/temp/myprog.txt --args XYZ

> # I am using command line arguments
> Args <- commandArgs(TRUE);
>
> # Args[1] is the desired dataframe name
> print(Args[1]);
[1] "XYZ"
>
> # Create a simple dataframe
> df <- c(c(1,2),c(3,4));
> print(df);
[1] 1 2 3 4
>
> # Save it
> path <- 'c:/temp/mydata.rdata'
> save(df, file=path);
>
> # Clear dataframe so I can see if it
> # is really populated by the load
> rm(df);
>
> # Load the dataframe from disk
> load(path);
>
> # Did you get it?
> print(df);
[1] 1 2 3 4
>
> # --- This is where things start to go bad ---
> # --- I know this is wrong, and I know why ---
> # --- but it should make clear what it is  ---
> # --- I am attempting to do.               ---
>
> # Copy it to dataframe with name passed from command line
> assign(Args[1], df);
>
> # Write it to disk with the new name
> save(list=Args[1], file=path);
>
> # Clear memory so I can see if the dataframe
> # is really populated by the load
> rm(df);
> rm(XYZ);
>
> # Load the dataframe from disk
> load(path);
>
> # Did you get it?  Is its name as expected?
> # (In subsequent processing I will be able to
> # hard code the name as shown here.)
> print(XYZ);
[1] 1 2 3 4
>

Ответы [ 3 ]

2 голосов
/ 09 марта 2012

Попробуйте

assign(Args[1],df)

(см. ?assign).

Если Args[1] содержит строку 'XYZ', то вы сможете ссылатьсяк кадру данных с помощью XYZ.

например:

dfname <- 'XYZ' # your Args[1] I presume
df <- data.frame( a=runif(10) ) # random data frame

assign(dfname,df)

# now I can access df by typing XYZ:
XYZ
XYZ$a

# etc.

При сохранении save(df,...) не выполнит работу - он сохранит df с именем переменнойdf.

Вместо этого вы передаете имя переменной, которую хотите сохранить, используя аргумент list для сохранения.

Например:

save(list='XYZ',file='tmp.rda')

Когда вы тогда load('tmp.rda'), у вас будет переменная XYZ, содержащая все, что она содержала, когда вы ее сохранили.

Итак, для вас:

# to show it works:
path <- 'tmp.rda'
save(list=Args[1],file=path)

rm(list=ls())
load(path)
print(XYZ) # this will work.
0 голосов
/ 09 марта 2012

Сработает ли использование функций saveRDS и readRDS вместо попытки вставить ваш data.frame в произвольное имя?

Примерно так:

x <- data.frame(a=1:10, b=letters[1:10])
saveRDS('some.file.rds')
rm(x)

XYZ <- readRDS('some.file.rds')
## Carry on ...
0 голосов
/ 09 марта 2012

вместо

Args[1] <- df;

попробуйте это:

assign(Args[1],df)
...