سؤال

I have two vectors in R, e.g.

a <- c(2,6,4,9,8)
b <- c(8,9,4,2,1)

Vectors a and b are ordered in a way that I wish to conserve (I will be plotting them against each other). I want to remove certain values from vector a and remove the values at the same indices in b. e.g. if I wanted to remove values ≥ 8 from a:

a <- a[a<8]

... which gives a new vector without those values.

Is there now an easy way of removing values from the same indices in b (in this example indices 4 and 5)? Perhaps by using a data frame?

هل كانت مفيدة؟

المحلول

Something like this:

keep <- a < 8
a <- a[keep]
b <- b[keep]

You could also use:

keep <- which( a < 8 )

نصائح أخرى

If the vectors are logically part of the same data, use a data frame. It is better programming practice.

df <- data.frame(a = a, b = b)
df <- df[df$a < 8, ]

Otherwise, set another vector to be the indices removed:

keep <- a < 8
a <- a[keep]
b <- b[keep]

Why not:

d <- data.frame(a=a, b=b)
d <- d[d$a < 8, ]

Or even:

d <- subset(d, a < 8)

First remove the indices from b then from a

b <- b[a<8]
a <- a[a<8]

a<8 returns a vector which defines which indices are smaller than 8.

If this is purely for plotting, you can avoid messing with b and the x-axis by using NA .

a[a>8]<-NA

plot(b,a) #works for point or line graphs
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top