Quantcast
Channel: Active questions tagged r - Stack Overflow
Viewing all articles
Browse latest Browse all 201867

R: Create new column by finding all numbers that are more or less than another given number in the same column with a condition in a dataframe

$
0
0

I have the following df

df <- structure(list(position = c(44188968, 44188969, 44188970, 44188975, 
44188977, 44188978), code1 = c(1, 0, 1, 0, 0, 1)), class = "data.frame", row.names = c(NA, 
-6L))

>df
position code1
44188968    1
44188969    0
44188970    1
44188975    0
44188977    0
44188978    1

I would like to add another column code2 (1 if true, 0 otherwise) when the following condition is true:

  • for each position, check if the other positionsare located +/- 3 away. If true, the other position must have code1 = 1.

I would then obtain something like below

position code1  code2
44188968    1   1
44188969    0   1
44188970    1   1
44188975    0   0
44188977    0   1
44188978    1   0

Could you please instruct me on how to achieve such table ?

EDIT: I forgot to mention that my data contains NA values

position code1
44188968    1
44188969    0
44188970    1
44188975    0
44188977    0
44188978    1
NA          1
NA          0
44189323    NA

In case of NA values, code2 is also NA

Thank you in advance.


Viewing all articles
Browse latest Browse all 201867

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>