[R] The "condition has length > 1" issue for lists

jim holtman jholtman at gmail.com
Mon Oct 15 17:37:18 CEST 2007


Your logic test is not correct.  Here is what I think you want.  See
if it makes sense.

> x <- list()  # create some test data
> x[[1]] <- read.table(textConnection("1 2 3 4
+ 5 6 7 8
+ 4 3 2 1
+ 8 7 6 5"))
> # create another list element
> x[[2]] <- t(x[[1]])
> str(x[[1]])
'data.frame':   4 obs. of  4 variables:
 $ V1: int  1 5 4 8
 $ V2: int  2 6 3 7
 $ V3: int  3 7 2 6
 $ V4: int  4 8 1 5
> x[[1]]
  V1 V2 V3 V4
1  1  2  3  4
2  5  6  7  8
3  4  3  2  1
4  8  7  6  5
> # assume all numeric -- test if any less than 3
> # case 1
> x[[1]] < 3  # you get multiple values back
        V1    V2    V3    V4
[1,]  TRUE  TRUE FALSE FALSE
[2,] FALSE FALSE FALSE FALSE
[3,] FALSE FALSE  TRUE  TRUE
[4,] FALSE FALSE FALSE FALSE
> # really want a single value
> any(x[[1]] < 3)
[1] TRUE
> # I think this is what you want
> newlist <- list()
> if (any(x[[1]] > 1) & any(x[[2]] > 1)){
+     newlist[[1]] <- x[[1]] - x[[2]]
+ }
> newlist
[[1]]
  V1 V2 V3 V4
1  0 -3 -1 -4
2  3  0  4  1
3  1 -4  0 -5
4  4 -1  5  0



On 10/15/07, Svempa <fempa at yahoo.com> wrote:
>
> I have the following code:
>
> list1 <- list()
> for (i in list.files(pattern="filename1")){
>    x <- read.table(i)
>        list1[[i]] <- x
> }
>
> list2 <- list()
> for (i in list.files(pattern="filename2*")){
>    x <- read.table(i)
>        list2[[i]] <- x
> }
>
> anslist <- vector('list', length(list1))
> for(i in 1:length(list1))
> if (list1[[i]] & list2[[i]] >1)
> anslist[[i]] <- list1[[i]] - list2[[i]]
>
> That, if at least one element in either of the lists is below 1, nothing
> happens. I now get the warning message "the condition has length >1..." etc.
> I would guess this is because list1 and list2 aren't really real matrices,
> more references to files. How do I get around this?
>
> --
> View this message in context: http://www.nabble.com/The-%22condition-has-length-%3E-1%22-issue-for-lists-tf4625785.html#a13209531
> 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 you are trying to solve?



More information about the R-help mailing list