[R] error when copy and transform within a data frame

jim holtman jholtman at gmail.com
Mon Jul 19 13:51:15 CEST 2010


Look at the error messages generated and you will see:

Error in data.frame(list(a = c(1, 2, 3), b = c(2, 3, 4), c = c(2L, 1L,  :
  arguments imply differing number of rows: 3, 2
In addition: Warning messages:
1: In if (x == "Yes") { :
  the condition has length > 1 and only the first element will be used
2: In if (x == "Yes") { :
  the condition has length > 1 and only the first element will be used
3: In if (x == "No") { :
  the condition has length > 1 and only the first element will be used

This indicates that you had an 'if' statement with more than one
logical value in its result.  Take a close look at the help page for
'if'.


You need to use 'ifelse' for vectorized testing:

a=c(1,2,3)
b=c(2,3,4)
c=c("Yes","No","Yes")
d=c("No","Yes","No")

df=data.frame(a,b,c,d)

# the following works fine!
df1 = transform(df, new=sapply(df[,c(1,2)], FUN = function(x) { x^2 } ))

# but the following doesn't work:

num_value = function(x) {
    ifelse(x == "Yes", 1, ifelse(x == "No", 0, NA))
}

df2 = transform(df, new=sapply(df[,c(3,4)], FUN = num_value ))


On Mon, Jul 19, 2010 at 4:46 AM, Al R <anevare1 at yahoo.com> wrote:
>
> # trying to do a copy and a transform within a data frame, but getting the
> "arguments imply differing number of rows" error, and I'm not sure why
>
> a=c(1,2,3)
> b=c(2,3,4)
> c=c("Yes","No","Yes")
> d=c("No","Yes","No")
>
> df=data.frame(a,b,c,d)
>
> # the following works fine!
> df = transform(df, new=sapply(df[,c(1,2)], FUN = function(x) { x^2 } ))
>
> # but the following doesn't work:
>
> num_value = function(x) {
>        if (x == "Yes") { return(1) }
>        else  if (x == "No") { return(0) }
>        else return(NA)
> }
>
> df = transform(df, new=sapply(df[,c(3,4)], FUN = num_value ))
>
> # generates this error..
> Error in data.frame(list(a = c(1, 2, 3), b = c(2, 3, 4), c = c(2L, 1L,  :
>  arguments imply differing number of rows: 3, 2
>
> # thanks for the help!
>
> --
> View this message in context: http://r.789695.n4.nabble.com/error-when-copy-and-transform-within-a-data-frame-tp2293686p2293686.html
> Sent from the R help mailing list archive at Nabble.com.
>
> ______________________________________________
> R-help at 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.
>



-- 
Jim Holtman
Cincinnati, OH
+1 513 646 9390

What is the problem that you are trying to solve?



More information about the R-help mailing list