r - R 中的函数、For 循环和条件

标签 r function for-loop if-statement

我得到了一个 .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*- 如何调用/打印列名称?我不认为它是 names(x) 但我不太确定除此之外还会是什么。

3- return () 是否正确?它是否应该从变量返回整个 for 循环(一旦我弄清楚如何将它与实际问题联系起来)?

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

这是示例代码的图像,因此就括号/语法而言,它更容易阅读:
enter image description here

最佳答案

我认为这个问题是出于教育目的,因此提供一个简单的 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 "

关于r - R 中的函数、For 循环和条件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61732242/

相关文章:

swift - 如何在 button.addTarget Action 中发送多个按钮? swift 3

python - 如何使用 NOAA API 查询给定坐标集的过去天气数据

r - 在 DataTable 输出中使用 Shiny 输入

r - 如何向重复的字符串添加字符然后将其删除

PHP 计算单词数比 str_word_count 更好

python - 多余的 python 参数

xml - 解析 xml 以在 R : how to consistently access nodes when xml structure varies? 中列出

javascript - "for (… in …)"循环中的元素顺序

windows - 对文件夹中的所有文件执行命令

c - 如何求数组[x] = 数组[x] + 1