Shrilaxmi M S
Shrilaxmi M S

Reputation: 171

R how to do division from one dataframe to another dataframe corresponding column name

Hello I wanted devide the one dataframe value from another datframe by its corrsponding column

Df

   std1 std2 std3 std4
     1    4    4   10
     2    10   6   20

df2

   std1 std2 std3 std4
    1     2   2    10

output=

    std1 std2 std3 std4
     1    2    2   1
     2    5    3   2

I have tried output=Df/df2 I got a error anyone help me to resolve this

Upvotes: 2

Views: 811

Answers (4)

GKi
GKi

Reputation: 39647

When df2 has only one row sweep could be used:

sweep(Df, 2, unlist(df2), "/")
#  std1 std2 std3 std4
#1    1    2    2    1
#2    2    5    3    2

or using col:

Df / df2[col(Df)]
#  std1 std2 std3 std4
#1    1    2    2    1
#2    2    5    3    2

Data:

Df <- read.table(header=TRUE, text="std1 std2 std3 std4
     1    4    4   10
     2    10   6   20")

df2 <- read.table(header=TRUE, text="std1 std2 std3 std4
    1     2   2    10")

Upvotes: 2

Karthik S
Karthik S

Reputation: 11584

Does this work:

df1/rbind(df2,df2)
  std1 std2 std3 std4
1    1    2    2    1
2    2    5    3    2

Data used:

df1
  std1 std2 std3 std4
1    1    4    4   10
2    2   10    6   20
df2
  std1 std2 std3 std4
1    1    2    2   10

Upvotes: 0

Rui Barradas
Rui Barradas

Reputation: 76402

Here is a S3 class solution.

`/.data.frame` <- function(x, y){
  if(is.null(dim(y))){
    x[] <- Map('/', x, y)
  } else {
    i <- intersect(names(x), names(y))
    if(length(i) == 0){
      xname <- deparse(substitute(x))
      yname <- deparse(substitute(y))
      warn <- sprintf("%s and %s have no common columns, returning %s", xname, yname, xname)
      warning(warn)
    } else{
      x[i] <- Map('/', x[i], y[i])
    }
  }
  x
}

Df / df2
#  std1 std2 std3 std4
#1    1    2    2    1
#2    2    5    3    2

df3 <- as.data.frame(matrix(1:3, ncol = 1))
Df / df3
#  std1 std2 std3 std4
#1    1    4    4   10
#2    2   10    6   20
#Warning message:
#In `/.data.frame`(Df, df3) :
#  Df and df3 have no common columns, returning Df

Df / 1:2
#  std1 std2 std3 std4
#1    1    2    4    5
#2    2    5    6   10

Upvotes: 1

Ronak Shah
Ronak Shah

Reputation: 388862

As direct division is possible only for dataframes with same dimension, you can repeat the rows in df2.

df1/df2[rep(nrow(df2), nrow(df1)), ]

#  std1 std2 std3 std4
#1    1    2    2    1
#2    2    5    3    2

Some other alternatives to this are -

df1[] <- Map(`/`, df1, df2)
df1[] <- purrr::map2(df1, df2, `/`)
df1 <- purrr::map2_df(df1, df2, `/`)

If the column names are not always ordered, you can first arrange any one of the dataframe with df2 <- df2[names(df1)] before using the above answer.

Upvotes: 2

Related Questions