【问题标题】:In R how do I create a variable whose contents are based on what is in other variables?在 R 中,如何创建一个变量,其内容基于其他变量中的内容?
【发布时间】:2020-09-20 13:58:18
【问题描述】:

我有一个包含治疗列表(治疗变量)的数据集,然后另一个人根据它们的作用机制(机制变量)对这些治疗进行了分类。我想添加另一种作用机制类别(体温过低),我正在努力这样做。

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

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 的新变量,查看治疗中的药物,如果你看到 Hypothermia 然后将 Hypothermia 放入新变量中,如果它没有说 Hypothermia 那么就写降低原来的作用机制”。但是我的输出看起来像这样:

[1]“体温过低”“2”“1”“2”“3”“4”

当我希望它看起来像这样时:

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

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

【问题讨论】:

  • 把你的数据变成字符,它们现在是因素。在您的示例中,您可以执行 df &lt;- data.frame(Treatment, Mechanism, stringsAsFactors = FALSE) 并尝试您的尝试
  • 您也可以将您的 R 版本升级到 4.0。 stringsAsFactors = FALSE 现在是默认值。

标签: r if-statement dplyr


【解决方案1】:

您可以使用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))

这是什么:

# 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 

【讨论】:

  • 非常感谢您!我在踢自己,解决方案是如此简单!我想我现在应该开始一直使用 tibbles...
猜你喜欢
  • 1970-01-01
  • 2021-02-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-02-09
  • 2015-08-01
  • 1970-01-01
  • 2020-12-15
相关资源
最近更新 更多