Dear Rxperts...
I would like to conditionally include an element (as a column) in a
dataframe. Please see the sample code below:
There is a correction to the earlier post.. my apologies...
a1 <- data.frame(P=rep(1,10),Qr=LETTERS[1:10],b=letters[1:10],
R=rep(c("A","B"),each=5))
lc1 <- list(C1 = "P",C2 =
ifelse(is.element("Q",names(a1)),"Q",ifelse(is.element("b",names(a1)),"b",NULL)),C3="R")
lc2 <- list(C1 = "P",C2 =
ifelse(is.element("Q",names(a1)),"Q",ifelse(is.element("b",names(a1)),"b",NULL)),
C3=ifelse(is.element("Ra",names(a1)),"Ra",NULL))
*The error for the above:*
Error in ifelse(is.element("Ra", names(a1)), "Ra", NULL) :
replacement has length zero
In addition: Warning message:
In rep(no, length.out = length(ans)) :
'x' is NULL so the result will be NULL
a2 <- subset(a1, sel=unlist(lc1)) # this works
a3 <- subset(a1, sel=unlist(lc2)) # this doesn't work
Is there a way to dynamically include columns in a dataframe?
Regards,
santosh
On Fri, Jan 10, 2014 at 12:45 PM, Santosh <[email protected]> wrote:
> Dear Rxperts...
>
> I would like to conditionally include an element (as a column) in a
> dataframe. Please see the sample code below:
>
> a1 <-
> data.frame(P=rep(1,10),Qr=LETTERS[1:10],b=letters[1:10],R=rep(c("A","B"),each=5))
>
> lc1 <- list(C1 = "P",C2 =
> ifelse(is.element("Q",names(a1)),"Q",ifelse(is.element("b",names(a1)),"b",NULL)),C3="R")
> lc2 <- list(C1 = "P",C2 =
> ifelse(is.element("Q",names(a1)),"Q",ifelse(is.element("b",names(a1)),"b",NULL)),C3="Ra")
>
> a2 <- subset(a1, sel=unlist(lc1)) # this works
> a3 <- subset(a1, sel=unlist(lc2)) # this doesn't
>
> Is there a way to dynamically include columns in a dataframe?
>
> Regards,
> santosh
>
[[alternative HTML version deleted]]
______________________________________________
[email protected] 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.