0

If ID are the same, I want to enter the calculated value with Locate column in the new row. If ID are not same, I want to represent it as 0.

I tried with for statement, however i had a hard in work.

help me!! please. thank you

this is my data and what I want to do.

>ID Locate
>10 2333
>10 5555
>10 2330
>10 1355
>12 1332
>12 1233
>12 1112
>13 3213
>14 3222
>14 5123
>14 6321

what i want to is

>ID Locate  diff
>10 2333    0
>10 5555    3222
>10 2330    -3225
>10 1355    -975
>12 1332    0
>12 1233    -99
>12 1112    -121
>13 3213    0
>14 3222    0
>14 5123    1901
>14 6321    1198

this is my code....

rm <- c()
for ( i in 1:ncol(test))
  {for ( j in 1:nrow(test))
   {if(test[i,1]==test[i,2])
          {c(test[i,j]-test[i,j+1])}
         else
           0
    rm <- c(rm,i)}}
eun lee
  • 145
  • 8

2 Answers2

1

You can do this with diff. Here I am using diff both to compute the differences and to decide which IDs match.

myData$diff = 0
myData$diff[which(diff(myData$ID) == 0) + 1] = 
    diff(myData$Locate)[which(diff(myData$ID) == 0)]
myData
   ID Locate  diff
1  10   2333     0
2  10   5555  3222
3  10   2330 -3225
4  10   1355  -975
5  12   1332     0
6  12   1233   -99
7  12   1112  -121
8  13   3213     0
9  14   3222     0
10 14   5123  1901
11 14   6321  1198

Data:

myData = read.table(text="ID Locate
10 2333
10 5555
10 2330
10 1355
12 1332
12 1233
12 1112
13 3213
14 3222
14 5123
14 6321",
header=TRUE)
G5W
  • 36,531
  • 10
  • 47
  • 80
1

If your data is an R dataframe, you can use the popular tidyverse group of packages to make jobs like this a bit easier.

df %>%
    group_by(ID) %>%
    mutate(diff = Locate - lag(Locate))

This code results in

ID  Locate  diff
10  2333    NA
10  5555    3222
10  2330    -3225
10  1355    -975
12  1332    NA
12  1233    -99
12  1112    -121
13  3213    NA
14  3222    NA
14  5123    1901
14  6321    1198

If you really need 0 instead of NA, then you an just do

df %>%
    group_by(ID) %>%
    mutate(diff = Locate - lag(Locate)) %>%
    mutate(diff = ifelse(is.na(diff), 0, diff))
Curt F.
  • 4,690
  • 2
  • 22
  • 39