Neil
Neil

Reputation: 8247

how to perform row wise operation on different column in r

I have following dataframe in r

 count1      count2      count3
   0           12          11 
  12           13          44
  22           32          13

I want to calculate distance between count2,count1 and count3 and count2 as follows

 sqrt(abs(count2-count1) + abs(count3-count2))

to every row of dataframe. My desired dataframe is as follows

 count1      count2      count3     distance
   0           12          11       sqrt(abs(12-0)+abs(12-11))
  12           13          44       sqrt(abs(13-12)+abs(44-13))
  22           32          13       sqrt(abs(32-22)+abs(13-32))

the way I am doing it is with for loop

 for(i in 1:nrow(df)){
    df$distance[i] <- sqrt(abs(df$count1[i] - df$count2[i]) + abs(df$count2[i] - df$count3[i]))
   }

Is there any better way of doing above ?

Upvotes: 0

Views: 86

Answers (5)

akrun
akrun

Reputation: 886938

We can just use base R

df$distance <- with(df, sqrt(abs(count2 - count1) + abs(count3 - count2)))

Or with rowSums from base R

df$distance <-  sqrt(rowSums(abs(df[-1] - df[-length(df)])))

data

df <- structure(list(count1 = c(0L, 12L, 22L), count2 = c(12L, 13L, 
32L), count3 = c(11L, 44L, 13L)), .Names = c("count1", "count2", 
"count3"), class = "data.frame", row.names = c(NA, -3L))

Upvotes: 1

AK88
AK88

Reputation: 3026

df$distance = apply(df, 1,
                    function(x) sqrt(abs(x[2] - x[1]) + abs(x[3] - x[2])))
df

Upvotes: 1

Federico Manigrasso
Federico Manigrasso

Reputation: 1200

use dplyr package

pretty much the standard now

Here a working example using iris data (use dput(namedataset) to share your db)

library(dplyr)

iris[1:3] %>% mutate(res=sqrt(abs(Sepal.Length-Sepal.Width)))

Upvotes: 0

Mbr Mbr
Mbr Mbr

Reputation: 734

You can also do with data.table package :

library(data.table)

y <- data.table(count1 = c(0,12,22), count2 = c(12,13,32), count3 = c(11,44,13))

y[, distance := sqrt(abs(count2 - count1) + abs(count3 - count2))]

Results :

> y
   count1 count2 count3 distance
1:      0     12     11 3.605551
2:     12     13     44 5.656854
3:     22     32     13 5.385165

Upvotes: 0

Val
Val

Reputation: 7023

I guess the dplyr package is the way to go for that:

df <- data.frame(count1 = sample(1:100,10),count2 = sample(1:100,10),count3 = sample(1:100,10))


> df %>% mutate(distance=sqrt(abs(count2-count1) + abs(count3-count2)))
   count1 count2 count3 distance
1      79     59     54 5.000000
2      70     18     22 7.483315
3      31     13     57 7.874008
4      54     49     53 3.000000
5      94     67     77 6.082763
6      51     74     21 8.717798
7      33      4     24 7.000000
8      90     79     78 3.464102
9       6     64     98 9.591663
10     22     68     28 9.273618

Upvotes: 3

Related Questions