简体   繁体   中英

Creating a function called clean_data in R

I'm a new guy in the R world and had to create a vector. data <- rnorm(10, 0, 1) Next question asked for a loop so I did:

    for(i in 1:length(data)){
        if(data[i] > 0)
            print("postive")
        else
            print("negative")

But now it's asking for:

"Write a function called “clean data” that takes in a vector of numbers and returns a vector called “ret” of same length such that ret[i] = 1 if the input vector ith element was positive, and ret[i] = 0 otherwise. To get started, make a separate R Block for your function and use the following shell:

    clean data <- function(input){ # your code here [...]
# ...
# your code here [...] return(ret) }

Professor also recommends reusing the loop from earlier.

I believe this is what you are looking for. Please note how ifelse is being used in the function instead of if and else functions separately. As you can see, this function would work with numeric string as input, but I've added an instance of it running on the previous data you've created. But I would like to add that the purpose of these exercices is really to make we scratch our heads and try to work the problem out for ourselves, so I recommend you persist on trying next time :)

data <- rnorm(10, 0, 1)

for(i in 1:length(data)){
  if(data[i] > 0) print("positive") else print("negative") 
}

clean_data <- function(input){
  
  ret <- NULL
  for(i in 1:length(input)){
    ifelse(input[i] > 0, ret[i] <- 1 , ret[i] <- 0) # note ifelse structure
  }
  
  return(ret)
}

clean_data(data)

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