在R中,如何创建一个变量,其内容基于其他变量中的内容?
我有一个数据集,其中包含治疗列表(治疗变量),然后另一个人根据其作用机制(机制变量)对这些治疗进行分类。我想添加另一种作用机制类别(体温过低),我正在努力这样做 我制作了一个小数据框,作为一些治疗方法及其机制类别的示例在R中,如何创建一个变量,其内容基于其他变量中的内容?,r,if-statement,dplyr,mutate,R,If Statement,Dplyr,Mutate,我有一个数据集,其中包含治疗列表(治疗变量),然后另一个人根据其作用机制(机制变量)对这些治疗进行分类。我想添加另一种作用机制类别(体温过低),我正在努力这样做 我制作了一个小数据框,作为一些治疗方法及其机制类别的示例 Treatment <- c("Hypothermia", "CNS-1102", "Hypocapnia", "Dextrorphan", "Mannitol", "Caffeinol") Mechanism <- c("Other", "Excitotoxicit
Treatment <- c("Hypothermia", "CNS-1102", "Hypocapnia", "Dextrorphan", "Mannitol", "Caffeinol")
Mechanism <- c("Other", "Excitotoxicity", "Blood flow", "Excitotoxicity", "Fluid regulation", "Other")
df <- data.frame(Treatment, Mechanism)
Treatment您可以使用dplyr
将其设置为tibble
而不是data.frame
,这将起作用
library(dplyr)
Treatment <- c("Hypothermia", "CNS-1102", "Hypocapnia", "Dextrorphan", "Mannitol", "Caffeinol")
Mechanism <- c("Other", "Excitotoxicity", "Blood flow", "Excitotoxicity", "Fluid regulation", "Other")
df <- tibble(Treatment, Mechanism) # changed this
df %>%
mutate(Mechanism_extra = if_else(Treatment == "Hypothermia", "Hypothermia", Mechanism))
库(dplyr)
处理使您的数据成为字符,它们现在是因素。在您的示例中,您可以执行df,也可以将R版本升级到4.0stringsAsFactors=FALSE现在是默认值。非常感谢!我真后悔解决办法这么简单!我想我现在应该开始一直使用tibbles。。。
library(dplyr)
Treatment <- c("Hypothermia", "CNS-1102", "Hypocapnia", "Dextrorphan", "Mannitol", "Caffeinol")
Mechanism <- c("Other", "Excitotoxicity", "Blood flow", "Excitotoxicity", "Fluid regulation", "Other")
df <- tibble(Treatment, Mechanism) # changed this
df %>%
mutate(Mechanism_extra = if_else(Treatment == "Hypothermia", "Hypothermia", Mechanism))
# A tibble: 6 x 3
Treatment Mechanism Mechanism_extra
<chr> <chr> <chr>
1 Hypothermia Other Hypothermia
2 CNS-1102 Excitotoxicity Excitotoxicity
3 Hypocapnia Blood flow Blood flow
4 Dextrorphan Excitotoxicity Excitotoxicity
5 Mannitol Fluid regulation Fluid regulation
6 Caffeinol Other Other