Foro de debate

Problema R

Problema R

de Kike Per -
Número de respuestas: 1


Hola a todos! Tengo un problema con un ejercicio de un curso que estoy haciendo de R. El problema es que el resultado no me da como vector. Espero que me alguien pueda ayudarme.  Abajo os pongo mis operaciones las cuales no me dan.

Gracias


EXERCISE :

A year is a leap year, if it can be divided by 4 but not by 100, except when it is divisible by 400. Create function ans(year1, year2), which returns all the leap years between year1 and year2. For example ans(2000,2010) should return vector c(2000,2004,2008). Number x is divisible by y if and only if the remainder is zero. In R you can use the operator %% to check if a number is exactly divisible by another number. Operator %% will return value 0 if and only if the number is divisible by other number. For example 100%%5 returns value 0 so 100 is divisible by 5. When you are ready input c.


Called from: question()


ans <- function(year1,year2){

 

for(year in year1:year2){

 

if((year %% 4 == 0) & (year %% 100 != 0) | (year  %% 400 == 0)){

 

return(year)

}

next

}

}




En respuesta a Kike Per

Re: Problema R

de Manuel Muñoz Márquez -

Buenas:

Al inicio de la función crea un vector vacío con la instrucción:

v <- numeric(0)

Luego, dentro del if, ve añadiendo años a ese vector con

v <- c(v, year)

Por último antes de la última llave, evalúa v. De esta forma v es devuelto por la función pues en R una función devuelve lo último evaluado.

Un saludo.