sashkello
sashkello

Reputation: 17871

R sequence in subset

I've got a data frame looking like this:

in    out
3234  1
124   1
323   0
532   1

Now I'd like to make a plot of mean(subset(data, data$in < x)$out). I attempt to generate a sequence for plotting like this:

x <- seq(0, 10000, by=1)
y <- mean(subset(data, data$in < x)$out)

But the second line gives me a warning "longer object length is not a multiple of shorter object length" and plot(x, y) results in an error. Meanwhile, if I put a number instead of x it works. Can anyone point out what's the problem with such approach?

Upvotes: 0

Views: 1359

Answers (1)

Didzis Elferts
Didzis Elferts

Reputation: 98449

You can use function sapply() to calculate mean for each element of x. But first changed column name of in to ins because it gave me an error.

colnames(data)<-c("ins","out")
x <- seq(0, 10000, by=1)
y <- sapply(x,function(x) mean(subset(data, ins < x)$out))
plot(x,y)

enter image description here

Upvotes: 3

Related Questions