R基础循环练习题

张剑

2020/04/04

Categories: Code Tags: R

R循环的几个练习题

有兴趣的同学可以把答案发给我。

1. Divisible by Ten

  1. Create a function named first_func() that takes a list of numbers named nums as a parameter.
  2. Return the count of how many numbers in the list are divisible by 10.
  3. first_func(c(0, 25, 30, 35, 40) 测试输出
first_func <- function(num){
  count = 0  # 初始化
  for (i in num ){
    if (i %% 10 == 0){
      count = count +1 
    }
  }
  return(count)
}
first_func(c(0, 25, 30, 35, 40))
## [1] 3

2.Greetings

  1. Create a function named sec_func() which takes a list of strings named names as a parameter.
  2. In the function, create an empty list that will contain each greeting. Add the string “Hello,” in front of each name in names and append the greeting to the list.
  3. Return the new list containing the greetings.
  4. 测试输出 sec_func(c(‘张’,‘李’,‘王’))
sec_func <- function(names){
  kong = c()
  for(i in names){
    k = paste("Hello, ",i)
    kong = append(kong,k)
  }
  return(kong)
}
sec_func(c('张','李','王'))
## [1] "Hello,  张" "Hello,  李" "Hello,  王"

3. Delete Starting Even Numbers

  1. Write a function called thrid_func() that has a parameter named lst

  2. The function should remove elements from the front of lst until the front of the list is not even. The function should then return lst.

  3. For example if lst started as [4, 8, 10, 11, 12, 15], then delete_starting_evens(lst) should return [11, 12, 15].

  4. Make sure your function works even if every element in the list is even!

  5. 测试输出third_func(c(4, 8, 10, 11, 12, 15))和third_func(c(4,8,10))


third_func <- function(lst){
  for (i in lst){
    if (i %% 2 == 0){
      lst = lst[-1]
    } else {break}
  }
  return(lst)
}
third_func(c(4, 8, 10, 11, 12, 15))
## [1] 11 12 15
third_func(c(4,8,10))
## numeric(0)

4. Odd Indices

  1. Create a function named fourth_func() that has one parameter named lst.
  2. The function should create a new empty list and add every element from lst that has an odd index. The function should then return this new list.
  3. For example, fourth_func(c(4, 3, 7, 10, 11, -2)) should return the list c(4, 7, 11).

fourth_func<-function(lst){
  new_list = c()
  for (i in seq(1:length(lst))){
    if (i %% 2 != 0 ){
      new_list = append(new_list,lst[i])
    }
  }
  return(new_list)
}
fourth_func(c(4, 3, 7, 10, 11, -2))
## [1]  4  7 11

5. Exponents

  1. Create a function named firth() that takes two lists as parameters named bases and powers. Return a new list containing every number in bases raised to every number in powers.
  2. For example, bases = c(2,3,4), powers=c(1,2,3)
  3. 结果应该展示(2, 4, 8, 3, 9, 27, 4, 16, 64)
  4. It would first add two to the first. Then two to the second. Then two to the third, and so on.
firth <- function(bases,powers) {
  res = c()
  for (i in bases){
    for (j in powers){
      res = append(res,i**j)
    }
  }
  return(res)
}
firth(c(2,3,4),c(1,2,3))
## [1]  2  4  8  3  9 27  4 16 64