0
votes

I want to make a vector of sums where sum would be a number of 1s in one column in one df if another column from the same df has values equal or greater with a column from a different df in which I actually want to write vector.

I have something like this

DF1$A <- c( 0.12 , 0.29, 0.36, 0.55)  
DF2
x <- c(0,0,1,0,1,0,1,0,0,1)
y <- c(0.11, 0.55, 0.23,0.33,0.59,0.66,0.88,0.11,0.05,0.90)

I want to make a vector DF1$B

DF1B<- sum(DF2$Y >= DF1$A & DF2$X == 1)

Problem is that I get a vector of one value and I want every value of the vector to be different based on a condition that is also a vector.

Also, I am getting this massage l

longer object length is not a multiple of shorter object length.

2
Just try it in the console and you will see yourself ... c(1:4) >= c(1:10), you have to care about what you are comparing, length matters. - Petr Matousu

2 Answers

0
votes

Ones and zeros serve as logical values, and so giving a numeric vector positions in logical terms would only take the elements correcponding to the TRUE or 1 positions.

as.logical(x)
# FALSE FALSE  TRUE FALSE  TRUE FALSE  TRUE FALSE FALSE  TRUE

y[as.logical(x)]
# 0.23 0.59 0.88 0.90

sum(y[as.logical(x)])
# 2.6
0
votes

Just read the warning message and try it in the console and you will see yourself ...

c(1:4) >= c(1:10)
 [1]  TRUE  TRUE  TRUE  TRUE FALSE FALSE FALSE FALSE FALSE FALSE
Warning message:
In c(1:4) >= c(1:10) :
  longer object length is not a multiple of shorter object length

you have to care about what you are comparing, length matters.

This should be ok ...

c(1:4) >= c(1:4)

This should be ok as well

c(1:4) >= c(1:8)

or

c(c(1:4),c(1:4)) >= c(1:4)

Some time you would like to compare one row with many rows, expecting the length of the rows is the same. So this is why you see that warning. Length matters and in your case, the length of longer is not multiple of shorter object length.

BTW

The length related commands are length for vectors and lists, nrow, ncol, dim for tables like objects.