1

I extract certain values out of dataset Z (the positions are given in dataset A) using a loop function.

#Exemplary datasets
Z <- data.frame(Depth=c(0.02,0.04,0.06,0.08,0.10,0.12,0.14,0.16,0.18,0.2), 
Value=c(10,12,5,6,7,4,3,2,11,13))
A <- data.frame(Depth=c(0.067, 0.155))

for (n in c(1:nrow(A)))
+ {find_values <- Z$Value[Z$Depth>=A$Depth[n]][1]
+ print(find_values)}

#Result
[1] 6
[1] 2

The result seems to consist of values in two seperate vectors. How can I merge them in an easy way to one vector as follows?

[1] 6, 2

Thanks in advance!

2 Answers 2

1

For your code to work as it is you can store them using index in for loop

for (n in seq_len(nrow(A))) {
   find_values[n] <- Z$Value[Z$Depth>=A$Depth[n]][1]
}
find_values
#[1] 6 2

However, you can simplify this with sapply by doing

sapply(A$Depth, function(x) Z$Value[which.max(Z$Depth >= x)])
#[1] 6 2
Sign up to request clarification or add additional context in comments.

Comments

0

We can use a vectorized approach

Z$Value[findInterval(A$Depth, Z$Depth) + 1]
#[1] 6 2

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.