在R中,我如何创建一个变量,其内容是基于其他变量的内容?

问题描述 投票:0回答:1

我有一个数据集,其中包含了一系列的治疗方法(Treatment变量),然后另一个人根据这些治疗方法的作用机制对其进行了分类(Mechanism变量)。我想添加另一个作用机制类别(低温),但我很难做到这一点。

我做了一个小的数据框架,作为一些治疗方法及其机制类别的例子。

Treatment <- c("Hypothermia", "CNS-1102", "Hypocapnia", "Dextrorphan", "Mannitol", "Caffeinol")
Mechanism <- c("Other", "Excitotoxicity", "Blood flow", "Excitotoxicity", "Fluid regulation", "Other")
df <- data.frame(Treatment, Mechanism)

我对低体温感兴趣,所以我想创建一个新的变量(称为Mechanism_extra),它是Mechanism的副本,只是它将 "低体温 "作为自己的类别,而不是将 "低体温 "病例归入 "其他 "类别。我的实际数据集包含了大约8000个条目,所以我无法手动完成。我试着用dplyr的mutate和ifelse来做这件事,但我的输出就是不成功。

df <- mutate(df, Mechanism_extra = ifelse(df$Treatment == "Hypothermia", "Hypothermia", df$Mechanism))
df$Mechanism_extra

在上面的代码中,我想说的是 "创建一个新的变量,叫做Mechanism_extra,看看Treatment中的药物,如果你看到Hypothermia,那么就把Hypothermia放到新的变量中,如果它没有写Hypothermia,那么就写下原来的作用机制"。然而我的输出是这样的。

[1] "Hypothermia" "2" "1" "2" "3" "4"

当我想让它变成这个样子。

[1]"低体温""兴奋毒性""血流""兴奋毒性""液体调节""其他"

为什么会有数字?我哪里做错了?

r if-statement dplyr mutate
1个回答
1
投票

你可以把它变成一个 tibble 而非 data.frame 使用 dplyr 就可以了。

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 
最新问题
© www.soinside.com 2019 - 2025. All rights reserved.