Dear Listers,

can anyone help me, please.

Since several days i try to figure out, how to assign values, vectors,
functions etc to variables with dynamically generated names inside of
functions.
Sometimes I succeed, but the success is rather arbitrary, it seems. up to
now i don't fully understand, why things like get, assign, <<- etc do
sometimes work, and sometimes not.

here's one of my daily examples, i am stuck with: Example 1 does work, but
example 2 doesn't?
How kann i tell R, that i want it to expand the string "dfb" to "dfb[,2]"
inside the function.
In the end i want the function to change the second variable of the
dataframe dfb permanently to factor (not just inside the function).

Thanks in advance!

Winfried


Example 1:
dfa <- data.frame(a=c(1:4),b=c(1:4))
dfa[,2] <- factor(dfa[,2])
is.factor(dfa[,2])
>TRUE

Example 2:
dfb <- data.frame(a=c(1:4),b=c(1:4))
f.fact <- function(x) {x[,2] <<- factor(x[,2])}
f.fact(dfb)
is.factor(dfb[,2])
>FALSE


PS: I tried a whole lot of other things like, ...
I really don't know where to keep on searching.


dfb <- data.frame(a=c(1,2,3,4),b=c(1,2,3,4))
f.fact <- function(x) {get(x)[,2] <<- factor(get(x)[,2])}
f.fact("dfb")
is.factor(dfb[,2])
> "Object 'x' nicht gefunden

dfb <- data.frame(a=c(1,2,3,4),b=c(1,2,3,4))
f.fact <- function(x) {get(x[,2]) <<- factor(x[,2])}
f.fact(dfb)
is.factor(dfb[,2])
> "Object 'x' nicht gefunden

dfb <- data.frame(a=c(1,2,3,4),b=c(1,2,3,4))
f.fact <- function(x) {get(x)[,2] <<- factor(x[,2])}
f.fact(dfb)
is.factor(dfb[,2])
> "Object 'x' nicht gefunden

dfb <- data.frame(a=c(1,2,3,4),b=c(1,2,3,4))
f.fact <- function(x) {assign(x[,2], factor(x[,2]))}
f.fact(dfb)
is.factor(dfb[,2])
> Ungültiges erstes Argument

dfb <- data.frame(a=c(1,2,3,4),b=c(1,2,3,4))
f.fact <- function(x) {quote(x)[,2], factor(x[,2])}
f.fact(dfb)
is.factor(dfb[,2])
> Unerwartetes ','

dfb <- data.frame(a=c(1,2,3,4),b=c(1,2,3,4))
f.fact <- function(x) {
name <- paste0(quote(x),"[,2]")
 assign(name, factor(x[,2]))}
f.fact(dfb)
is.factor(dfb[,2])
> FALSE

dfb <- data.frame(a=c(1,2,3,4),b=c(1,2,3,4))
f.fact <- function(x) {
name <- paste0(get(x),"[,2]")
assign(name, factor(x[,2]))}
f.fact("dfb")
is.factor(dfb[,2])
> Falsche Anzahl von Dimensionen

dfb <- data.frame(a=c(1,2,3,4),b=c(1,2,3,4))
f.fact <- function(x) {
 name <- paste0(x,"[,2]")
assign(name, factor(x[,2]))}
f.fact("dfb")
is.factor(dfb[,2])
> Falsche Anzahl von Dimensionen

ächz ...

        [[alternative HTML version deleted]]

______________________________________________
R-help@r-project.org mailing list
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.

Reply via email to