简体   繁体   中英

How to condition a computation and then add al computation done in R?

i am experimenting with and R and I can't find the way to do the next thing:

1- I want to multiply if x == 3 multiply by "y" value of the same row 2- Add all computations done in step 1.

  x <- 3426278722533992028364647392927338
  y <- 7479550949037487987438746984798374
  x <- as.numeric(strsplit(as.character(x), "")[[1]])
  y <- as.numeric(strsplit(as.character(y), "")[[1]])
  Table <- table(x,y)
  Table <- data.frame(Table)

  Table$Freq <- NULL

So I tried creating a function:

  Calculation <- function (x,y) {

  z <- if(x == 3){ x * y }

  w <- sum(z)

  }

x and y are the columns of the data.frame

This prints and error which I struggle to solve...

Thanks for your time,

Kylian Pattje

2 things here:

1. Use ifelse in your function,

Calculation <- function (x,y) {
  z <- ifelse(x == 3, x * y, NA)
  w <- sum(z, na.rm = TRUE)
  return(w)
}

2. Make sure your variables are NOT factors,

Table[] <- lapply(Table, function(i) as.numeric(as.character(i)))

Calculation(Table$x, Table$y)
#[1] 84

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM