R中的函数,For循环和条件

我得到了一个.csv数据集,我想使用for循环为数据建立一个函数。数据集有5列,数据由因子或数字组成。如果数据是一个因素,则什么也不做,只需打印出列名及其类即可。如果数据是数字,则打印出名称,类以及两个函数(我已经预先创建)。

我对如何组织函数/ for循环的语法有些迷惑。

p.data <- read.csv("file.csv")
function(
x){
for.loop.variable <- for(index in data.csv){
if (class(x)) == "factor" 
{cat("Name of Column is:", names(x*), "\n", 
"Class of Column is :" , (class(x)))
} else {
cat("Name of Column is:", names(x*), "\n", 
"Class of Column is :" , (class(x)),"\n", 
"Function 1 is :", function.1(x), "\n",
"Function 2 is :", function.2(x), "\n")
}
}
}
return (for.loop.variable)

我认为这是正确的设置,但我有3个似乎无法弄清楚的问题:

1- for循环迭代如何发挥作用?我根本没有在条件语句中引用它,而且我不确定该怎么做?

2 *-如何调用/打印列名?我不认为它是名称(x),但我不太确定它会是什么。

3- return()是否正确?它是否应该从变量返回整个for循环(一旦我弄清楚如何将其绑定到实际问题中)?

请让我知道在哪里修复错误,以便我可以正确学习。

Here's an image of the example code so it's a bit easier to read as far as brackets/syntax goes: enter image description here

评论
  • C大调
    C大调 回复

    我认为这个问题是出于教育目的,因此提出了一个简单的for循环:

    class_print <- function(df){
    
      for(i in 1:ncol(df)){
        if(is.factor(df[,i])){
          print(paste0("Name of column is ", names(df[i]), "class is factor ",collapse = ""))
        }
        else{
         print(paste("Name of column is ", names(df[i]),"class is ", class(df[,i]),collapse=""))
        }
    
      }
    
    }
    

    测试:

    class_print(iris)
    [1] "Name of column is  Sepal.Length class is  numeric"
    [1] "Name of column is  Sepal.Width class is  numeric"
    [1] "Name of column is  Petal.Length class is  numeric"
    [1] "Name of column is  Petal.Width class is  numeric"
    [1] "Name of column is Speciesclass is factor "