Cutting some part of my Vector

Hi everyone, sorry if my question is too basic or asked before. I am very new to this.
So I have a two sets of data, each stored in one vector. I need to tailor it, meaning to remove some of the initial data because it is meaningless. This is the code I wrote, but it doesn't work somehow. I would be more than grateful, is someone can tell me what is wrong with this, or tell me how I can make it cleaner and neater.

Variables:
Displacement and Force: two vectors where my big data is stored. Their length is equal.

Datanumber <- length(Displacement) # Initial amount of data
counter <- 1
while (counter < Datanumber) {
if (Force[counter+5] > Force[counter]+2 )
{
break
}
counter = counter + 1
}
Displacement <- Displacement [-c (1:(counter-10))]
Force <- Force [-c (1:(counter-10))]

Error: Error in [.data.frame(Force, counter + 5) : undefined columns selected

Hi!

To help us help you, could you please prepare a reproducible example (reprex) illustrating your issue? Please have a look at this guide, to see how to create one:

There is no need to take all the trouble of a while loop; the big benefit of using R is that pretty much everything is vectorized.

Consider this example:

cats <- c(10, 20, 30) # just some data...
dogs <- c(44, 55, 66) # ...yet more random data

test <- cats < 20 # condition being tested, output is a logical vector

result <- c(cats[test],  # cats meeting the condition
            dogs[!test]) # dogs replacing cat failures

print(result)

It compares two numeric vectors, named cats & dogs (or what not). Indexes of cats meeting a condition are stored in vector test, and then cats meeting the condition are combined with dogs for the position where the test was failed (so the total length of vector remains the same).

1 Like

Hi, thanks for the answer. I understood what you mean, but I guess it's not what I want. I want to find a threshhold in my data, and I don't wanna remove all the data that are for instance lower than 5.
The data is something like this:
1 1 1 1 1 1 1 2 1 2 1 2 3 4 5 10 100 140 ... 120 100 4 1 1 2

So I want to find the first 3, or the first 2. I don't want to remove all of the 2s or 3s.

Oki, (I think) I understand.

In that case you might find the function which() useful, such as in this example:

data <- c(1, 1, 1, 1, 1, 1, 1, 2, 1, 2, 1, 2, 3, 4, 5, 10, 100, 140)

asdf <- which(data == 1)[-1] # index of items in data equal to 1 (except the first)

data[-asdf] # return all items on data except those on index asdf

In this case it will find all the indexes of your vector where the item is equal to 1 (except for the first one - that is handled by the minus one in square brackets). Then it is just a matter of removing all the items on the index.

You will want to iterate this process - perhaps using a for cycle or what not.

1 Like

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.