tags:

views:

59

answers:

2

I have a function, as follows:

f.factor <- function(x) {
print(length(unique(x)))
z <- 1 
    for (i in 1:length(unique(x))) {
        z[i] <- readline(":")
    }
x <- factor(x, labels=c(z)) 
return(x)
}

Essentially, it allows me to copy/paste/type or just simply write into my script the factors for a particular variable without having to type c("..","...") a million times.

I've run into a problem when I try to use this function in a loop, perhaps the loop structure will not allow lines to be read within the loop?

for(i in 1:ncol(df.)) {
df[,paste("q4.",i,sep="")] <- f.factor(df[,paste("q4.",i,sep="")])
Never Heard of
Heard of but Not at all Familiar
Somewhat Familiar
Familiar
Very Familiar
Extremely Familiar
}

In the end, I'm looking for a way to specify the factor label without having to rewrite it over and over.

+2  A: 

That was only working before because when you pasted all the code in at the top level it was executed immediately and the readline() call used the following N lines. In a function, or any control structure, it will try to parse it as R code which will fail.

A multiline string can stand in for a passable heredoc:

lvls = strsplit('
Never Heard of
Heard of but Not at all Familiar
Somewhat Familiar
Familiar
Very Familiar
Extremely Familiar
', '\n')[[1]][-1]
Charles
+1  A: 

Instead of the for loop you can just use scan without a file name (and what='' and possibly sep='\n'.

> tmp <- scan(what='', sep='\n')
1: hello there
2: some more
3: 
Read 2 items
> tmp
[1] "hello there" "some more"  
> 
Greg Snow