R 在IF语句中执行多个操作
我想根据另一个变量的条件更改多个变量的值 比如:R 在IF语句中执行多个操作,r,if-statement,R,If Statement,我想根据另一个变量的条件更改多个变量的值 比如: df <- iris df$index <- row.names(df) if(df$index == 10){ df$Species <- "test"; df$Sepal.Length <- 100 } 并且变量保持不变。您正在使用的if语句看起来可以在for循环中工作。df$index==10返回一个向量,因此错误表示if语句将只处理该向量的第一个元素。下面的解决方案应该有效。子集是过滤器为真的数据,然后
df <- iris
df$index <- row.names(df)
if(df$index == 10){
df$Species <- "test";
df$Sepal.Length <- 100
}
并且变量保持不变。您正在使用的if语句看起来可以在for循环中工作。df$index==10返回一个向量,因此错误表示if语句将只处理该向量的第一个元素。下面的解决方案应该有效。子集是过滤器为真的数据,然后操纵该数据帧。然后删除此数据并将操纵的子集附加到数据框的底部。这将确保所有观测值在更改后仍保留在数据集中,但不能保证观测值保持相同的顺序
library(tidyverse)
df <- iris
df$index <- row.names(df)
subset <- df[df$index == 10, ]
subset$Species <- "test"
subset$Sepal.Length <- 100
df <- df[df$index != 10, ] %>%
rbind(subset)
目前,您所有的表达式在等式==或赋值运算符的两边都保持不同的长度,我认为这个答案可能更灵活。它使用tidyverse,您可以在此处了解更多信息:
检查这个:做这个工作。我想找一些更像SPSS中的“如果做”语句的东西,它是这样的:如果做性别情商'm'计算分数1=2*q1+q2+计算分数2=3*q1+q2。使用向量化的ifelse:df$Species
library(tidyverse)
df <- iris
df$index <- row.names(df)
subset <- df[df$index == 10, ]
subset$Species <- "test"
subset$Sepal.Length <- 100
df <- df[df$index != 10, ] %>%
rbind(subset)
df$Species[10] <- "test"
df$Sepal.Length[10] <- 100
library(tidyverse)
# specify condition if you want to use multiple times
y <- df$index == 10
df <- df %>% # this is a pipe. It plugs df into the next function, which is mutate
# mutate modifies variables in the df
mutate(
Species =
# case when can handle many conditions, though we just have one here
case_when(
y ~ "test",
# TRUE means if the condition is not met (or something like that, and we just return the original value)
TRUE ~ as.character(Species)),
# we treat each variable separately
Sepal.Length =
case_when(
y ~ 100,
TRUE ~ as.double(Sepal.Length))
)