如果“哪个”功能找不到值怎么办?

时间:2019-02-20 23:44:29

标签: r statistics

error message 当which函数找不到值时,出现此错误。我希望它简单地返回一个值,表明什么也没找到。我该怎么做? 我也想使用一个for循环来重复遍历数据框中的每个变量,我将如何分别查看数据框中的每一列?我只需要知道如何调用矩阵的列或行,就可以使用循环了-我已经编程多年了,对r来说只是一个新手。谢谢!

Day1 = c("S", "Be", "N", "S", "St")
Day2 = c("S", "S", "M", "Ta", "Sa")
Day3 = c("S", "Ba", "E", "Te", "U")
Day4 = c("V")

Week = data.frame(Day1, Day2, Day3, Day4)
print(Week)

n = which(Week$Day4 == "S")

if (n[1] == 1) {
  print("true")
} else {
  print("false")
}

1 个答案:

答案 0 :(得分:1)

which()函数的输出是一个向量,因此如果找不到which()函数的值是integer(0),那么我建议不要在if中使用语句n[1] == 1更改为if( length(n) > 0 ),这意味着给定列中存在匹配项。

第二个问题是一种简单的方法,即使用data.frames的索引遍历列

n_columns <- ncol(Week) 

# this will iterate through all the columns.
for( i in 1:n_columns ){
 idx <- which(Week[ , i] == "S")
}

显然,这将更新每个迭代中的idx值,因此,如果要保存'true'/'false'打印件,则希望将True,False输出保存在向量中。

在代码中,方括号表示Week[ rows , columns],如果没有像我的示例Week[ , i ]这样的输入,则表示您要获取列i的所有行。

希望这会有所帮助!

相关问题