Question

I want to create an array using sapply in R. But I am using 3 vectors in a data frame. For instance, I want to generate x(i)=0 if a(i) +b(i)+c(i)==0 ,where a, b and c are vectors from the data frame. Is this possible with sapply or mapply?

Was it helpful?

Solution 2

Assuming x is pre-initialized to be all ones, and df is the data frame that contains a, b, and c, then a simple solution is:

x[with(df, a + b + c == 0)] <- 0

Here we generate an index vector that contains TRUE whenever the desired condition is met (a + b + c == 0), and then use that to replace those values with zero in x. With the data frame generated by @Shambho, we get:

[1] 1 1 0 1 1 0 1 1 1 1

OTHER TIPS

Here is a possibility:

set.seed(10)
vex <- data.frame(
  a=sample(-1:1,size=10,replace=T),
  b=sample(-1:1,size=10,replace=T),
  c=sample(-1:1,size=10,replace=T)
  )
vex

x <- sapply(1:nrow(vex), function(i) ifelse(sum(vex[i,]==0),0,1))
x

Since vex is a data.frame with columns a, b and c, sum(vex[i,]) will add the i'th row, and is equivalent to a[i]+b[i]+c[i]!

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top