[英]Creating a function called clean_data in R
I'm a new guy in the R world and had to create a vector.我是 R 世界的新手,必须创建一个向量。
data <- rnorm(10, 0, 1)
Next question asked for a loop so I did: data <- rnorm(10, 0, 1)
下一个问题要求循环,所以我做了:
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”的函数,它接收一个数字向量并返回一个长度相同的名为“ret”的向量,如果输入向量第 i 个元素为正,则 ret[i] = 1,并且 ret[i] = 0 否则。要开始,请为您的函数创建一个单独的 R 块并使用以下 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.
请注意如何在函数中使用 ifelse 而不是 if 和 else 函数。 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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.