[R] Function argument and scope
Jim Lemon
drjimlemon at gmail.com
Mon Nov 14 08:55:54 CET 2016
Hi Bernardo,
I don't think that your function is doing anything like you expect it to do:
test <- data.frame(var1=c("a","b","c"),var2=c("d","e","f"))
test
var1 var2
1 a d
2 b e
3 c f
You have a data frame with two columns, the first thing you do is
extract the first value in the first column:
test[1,1]
[1] a
Levels: a b c
Okay, looks like the first column is a factor. The next operation,
strsplit, requires a character argument
strsplit(test[1,1]," ")
Error in strsplit(test[1, 1], " ") : non-character argument
Not what you have. Go back to the beginning and create the data frame
without the values becoming factors:
test <- data.frame(var1=c("a","b","c"),var2=c("d","e","f"),
stringsAsFactors=FALSE)
> strsplit(test[1,1]," ")
[[1]]
[1] "a"
Now strsplit doesn't complain, but just gives you back the first
value. As it is only of length 1, the conditional fails and the
function returns the initial data frame. Try as I might, I cannot work
out what you are trying to do, so I will await further information.
Jim
On Mon, Nov 14, 2016 at 9:09 AM, Bernardo Doré <berdore at gmail.com> wrote:
> Hello list,
>
> my first post but I've been using this list as a help source for a while.
> Couldn't live without it.
>
> I am writing a function that takes a dataframe as an argument and in the
> end I intend to assign the result of some computation back to the
> dataframe. This is what I have so far:
>
> myFunction <- function(x){
> y <- x[1,1]
> z <- strsplit(as.character(y), split = " ")
> if(length(z[[1]] > 1)){
> predictedWord <- z[[1]][length(z[[1]])]
> z <- z[[1]][-c(length(z[[1]]))]
> z <- paste(z, collapse = " ")
> }
> x[1,1] <- z
> }
>
> And lets say I create my dataframe like this:
> test <- data.frame(var1=c("a","b","c"),var2=c("d","e","f"))
>
> and then call
> myFunction(test)
>
> The problem is when I assign x[1,1] to y in the first operation inside the
> function, x becomes a dataframe inside the function scope and loses the
> reference to the dataframe "test" passed as argument. In the end when I
> assign z to what should be row 1 and column 1 of the "test" dataframe, it
> assigns to x inside the function scope and no modification is made on
> "test".
>
> I hope the problem statement is clear.
>
> Thank you,
>
> Bernardo Doré
>
> [[alternative HTML version deleted]]
>
> ______________________________________________
> R-help at r-project.org mailing list -- To UNSUBSCRIBE and more, see
> 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.
More information about the R-help
mailing list