How to create new column based on another column's contents in R -
This is a sample of my data set:
& gt; Data C 1 C 2 C3C4C5C6Aatom 1 -4.7 9 4 -7.29 6.756C ATOM1-4.357-6.181 6.473 O ATM 2 -5.878 -8.511 5.233 C ATM 2 -7.02-9.179 5.732 C Atom 3 -7.479-9.499 6.108 C ATM 5 -4.873 -7.021 6.767 C Atom 8 -3.891 -6.723 6.31 O Atom 1 -7.515 -10.402 -0.621 C ATM 1 -7.26 -11.716 -0.22 o Atom 2 -7.53 -10.348 0.581 C Atom 3 -6.689 -11.008 2.344c
Finally, what I want to achieve is to have a new column, when reset to number 1 in C2, as shown below Gone:
& gt; Data C1 C 2 C3C4C5C6C7Aatom 1 -4.7 9 4 -7.29.6756C1Atom1-4.357-6.181 6.473O1Atom2-5.878-8.511 5.233C1Atom2-7.02- 9 .179 5.732 C1 Atom 3 -7.479-949 9910.108C1 ATO M5 -4.873 -7.021 6.767C1 Atom8-3.891 -6.723 6.31 O 1 Atom 1 -7.515 -10.402 -0.621 Sea Atom 1 -7.26 -11.716 -0.22 O 2 Atom 2 -7.53 -10.348 0.581 C2 Atom 3 - 6.689 -11.008 2.344 C2 I used the loop with the nested statement. My method was to compare an existing line with the following line if the value is less than the current value, then I allocate 1 for the new column - if not, I increase the old calculation of 1. C7 = NULL i & lt; - 1 index & lt; - {if data ($ c2 [i] & lt; = data $ c2 [i + 1]) for 1 (i in 1: nrow) {data $ c7 = index} else {data $ From C7 to & lt; - Index + 1}} ** This code does not work, and this error occurs when data ($ c2 [i] & lt; = data $ C2 [i + 1]):: unavailable value where TRUE / FALSE ** I do not believe what I am doing and I feel like there is a better way to do this. I appreciate any help - thanks in advance!
You do not need a loop:
Data $ C7 & Lt; - C (1, cumsum (data $ C2) & lt; 0) + 1) C1C2C3C4C5C6C7Aat 1 -4.794 -7.290 6.756C1 2Atom1 -4.357 -6.181 6.473 O 1 to 3 Atom 2 -5.878 -8.511 5.233 C1 to 4 Atom 2 -7.020-9.179 5.732 C1 to 5 Atom 3 -7.479 -9.499 6.108 C1 to 6 Atom 5 -4.873 -7.021 6.767 C 1 to 7 atom 8 -3.891 -6.723 6.310 is 1 to 8 atom 1 -7.515 -10.402 -0.621 c29 atom 1 -7.260 -11.716 -0.220 2 10 atom 2 -7.530 -10.348 0.581 c211 atom3-6.689 -11.008 2.344 c2
Comments
Post a Comment