变量值更改为“ ifelse”

时间:2019-07-15 03:26:05

标签: r

我想将变量“ month”更改为新的变量“ season”。 我尝试了如下两种方法,但似乎我的代码中有一些错误。

train_fd<-train_fd %>% mutate(season = ifelse(month <= 2 & month == 12,"winter",
                                         ifelse(month <= 5 & month > 3,"spring",
                                                ifelse(month <= 9 & month > 6,"summer","fall"))))

train_fd <- within(train_fd,
                  {
                    season = character(0)
                    season[month <= 2 & month == 12] = "winter"
                    season[month <= 5 & month >= 3] = "spring"
                    season[month <= 9 & month >= 6] = "summer"
                    season[month == 10 & month == 11] = "fall"
                    season = factor(season, level = c("winter","spring","summer","fall"))
                  })

我希望level的输出为c("winter","spring","summer","fall"),但实际输出为level

c("winter", "fall")

2 个答案:

答案 0 :(得分:0)

使用plugins { id("org.springframework.boot") version "2.1.6.RELEASE" id("io.spring.dependency-management") version "1.0.7.RELEASE" kotlin("jvm") version "1.2.71" kotlin("plugin.spring") version "1.2.71" } springBoot { mainClassName = "com.api.vmtest" } group = "com.api" version = "0.0.1-SNAPSHOT" java.sourceCompatibility = JavaVersion.VERSION_1_8 repositories { mavenCentral() } dependencies { implementation("org.springframework.boot:spring-boot-starter-web") implementation("com.fasterxml.jackson.module:jackson-module-kotlin") implementation("org.jetbrains.kotlin:kotlin-reflect") implementation("org.jetbrains.kotlin:kotlin-stdlib-jdk8") testImplementation("org.springframework.boot:spring-boot-starter-test") } tasks.withType<KotlinCompile> { kotlinOptions { freeCompilerArgs = listOf("-Xjsr305=strict") jvmTarget = "1.8" } } 运算符-

%in%

还建议您查看ifelse(month %in% c(1,2,12), "winter", ifelse(month %in% c(3,4,5), "spring", ifelse(month %in% c(6,7,8,9), "summer", "fall"))) 中的?case_when()

答案 1 :(得分:0)

坦白说,我会为自己编写一个显式词典省去很多麻烦:

m2s <- c( rep("winter", 2), 
          rep("spring", 3), 
          rep("summer", 4), 
          rep("fall", 2), "winter)

现在您可以简单地

train_fd$season <- m2s[ train_fd$month ]

请注意第一种方法中的问题:

  • month <= 2 & month == 12始终返回FALSE,因为您使用的是&而不是|;因此,一月,二月和十二月都变成了“秋天”;
  • month <= 5 & month > 3如果month == 3会怎样?然后三月是秋天...
  • month <= 9 & month > 6,六月变成秋天。

您的第二种方法将复制其中一些错误(例如冬天的&)并添加新的错误(例如条件month == 10 & month == 11,该错误始终返回FALSE)。但是,我没有丝毫想法,在任何一种方法中如何获得winter作为输出级别:这是不可能的。

最重要的是:多层条件句容易出现错字。