R:如何使用ifelse语句的字符向量 [英] R: How to use ifelse statement for a vector of characters

查看:127
本文介绍了R:如何使用ifelse语句的字符向量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用R来解决一个问题,但我的代码无法正常工作。我尝试调试,但似乎ifelse语句无法在某些数字上工作,这些数字似乎很随机。



这是测验: http://puzzles.nigelcoldwell.co.uk/six.htm



{pre> switch < - rep(off,100)
for(i in 1:100){
k < - c(seq(i, 100,i))
ifelse(switches [k] ==off,switches [k]< - on,switches [k] < - off)
}

当我运行这段代码时,我会打开14,22,26,30,34等在那里我应该有关闭。

解决方案

ifelse 语法应该是

 开关<  -  rep(off,100)
for(i in 1:100){
k < - seq(i,100,i)
switches [k] }


I am trying to solve a quiz using R, but my code does not work properly. I tried debugging, but it seems that the ifelse statement fails to work at certain numbers that seem pretty random.

Here is the quiz: http://puzzles.nigelcoldwell.co.uk/six.htm

switches <- rep("off", 100)
for(i in 1:100){
  k <- c(seq(i, 100, i))
  ifelse(switches[k] == "off", switches[k] <- "on", switches[k] <- "off")
}

When I run this code, I get "on" for 14, 22, 26, 30, 34, etc in which I should have got "off." Is there a mistake in the way I applied ifelse statement to a vector with vectorized index?

解决方案

The ifelse syntax should be

switches <- rep("off", 100)
for(i in 1:100){
  k <-  seq(i, 100, i)
  switches[k] <- ifelse(switches[k] == "off",  "on", "off")
}

这篇关于R:如何使用ifelse语句的字符向量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆