"7:9, 12:14" in dataframe to c(7:9, 12:14)

classic Classic list List threaded Threaded
2 messages Options
Reply | Threaded
Open this post in threaded view
|

"7:9, 12:14" in dataframe to c(7:9, 12:14)

Mikkel Grum
I want to do something like df[df$b %in% df2[i, 2], ]
where df$b is a numeric vector and df2[i, 2] is a
factor with
levels like "7:9, 12:14". For example:

a <- c(paste("A", 1:10, sep = ""), paste("B", 1:10,
sep = ""))
b <- 1:20
df <- as.data.frame(cbind(a, b))
df$b <- as.numeric(levels(df$b))[as.integer(df$b)]

f <- c("X", "Y", "Z")
g <- c("1:6", "7:9, 12:14", "18")
df2 <- as.data.frame(cbind(f, g))

i <- 2
df[df$b %in% df2[i, 2], ] # or
df[df$b %in% levels(df2)[as.integer(df2[i, 2])], ] #
this is the closest I've got

The results I want is given by
> df[df$b %in% c(7:9, 12:14), ]
    a  b
7  A7  7
8  A8  8
9  A9  9
12 B2 12
13 B3 13
14 B4 14

Can it be done?

Mikkel Grum

______________________________________________
[hidden email] mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide! http://www.R-project.org/posting-guide.html
Reply | Threaded
Open this post in threaded view
|

Re: "7:9, 12:14" in dataframe to c(7:9, 12:14)

PIKAL Petr
Hi

I knew I encountered it somewhere. Looking into my archives gave me
an answer of similar question by Prof.Ripley

So here you are

df[eval(parse(text=paste("c(",df2[2,"g"], ")"))),]

?eval
?parse

HTH
Petr



On 1 Jan 2006 at 23:27, Mikkel Grum wrote:

Date sent:       Sun, 1 Jan 2006 23:27:00 -0800 (PST)
From:           Mikkel Grum <[hidden email]>
To:             [hidden email]
Subject:         [R] "7:9, 12:14" in dataframe to c(7:9, 12:14)

> I want to do something like df[df$b %in% df2[i, 2], ]
> where df$b is a numeric vector and df2[i, 2] is a
> factor with
> levels like "7:9, 12:14". For example:
>
> a <- c(paste("A", 1:10, sep = ""), paste("B", 1:10,
> sep = ""))
> b <- 1:20
> df <- as.data.frame(cbind(a, b))
> df$b <- as.numeric(levels(df$b))[as.integer(df$b)]
>
> f <- c("X", "Y", "Z")
> g <- c("1:6", "7:9, 12:14", "18")
> df2 <- as.data.frame(cbind(f, g))
>
> i <- 2
> df[df$b %in% df2[i, 2], ] # or
> df[df$b %in% levels(df2)[as.integer(df2[i, 2])], ] #
> this is the closest I've got
>
> The results I want is given by
> > df[df$b %in% c(7:9, 12:14), ]
>     a  b
> 7  A7  7
> 8  A8  8
> 9  A9  9
> 12 B2 12
> 13 B3 13
> 14 B4 14
>
> Can it be done?
>
> Mikkel Grum
>
> ______________________________________________
> [hidden email] mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide!
> http://www.R-project.org/posting-guide.html

Petr Pikal
[hidden email]

______________________________________________
[hidden email] mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide! http://www.R-project.org/posting-guide.html