【问题标题】:Change values in data.frame conditionally有条件地更改 data.frame 中的值
【发布时间】:2015-09-06 15:11:13
【问题描述】:

我正在尝试检查一个变量的值,如果它满足某个条件,则将新变量设置为 1,否则将其设置为零。

我在 R 中遇到了困难。

这个简单的代码不起作用:

attach(data)
if (Drug = 1) {
   Drug_factor <- 0
} else {
   if (Drug = 2) {
      Drug_factor <- 1
   } else  Drug_factor<- 0

我不明白为什么这不起作用。 为什么 R 使用如此复杂的约定来做基本的事情?

【问题讨论】:

  • 请不要attach“数据”。您可以使用ifelse,即v1 &lt;- with(Data, ifelse(Drug==1, 0, ifelse(Drug==2, 1, 0))),甚至可以不使用两个ifelse。但是一个例子会很有用,因为我不知道你的数据是什么样子的。
  • 如果'Drug'中只有两个值,我们可以使用with(Data, factor(Drug, levels=1:2, labels=0:1)),也可以通过其他方式完成。

标签: r


【解决方案1】:

您可以使用ifelse

Data$Drug_factor <- with(Data, ifelse(Drug==1, 0, 1))

或使用factor 方法

Data$Drug_factor <- with(Data, as.numeric(as.character(factor(Drug, 
                levels=1:2, labels=0:1))))

或者

Data$Drug_factor <- c(0,1)[(Data$Drug==2)+1]

假设“药物”是“数字”,甚至更短

Data$Drug_factor <- c(0,1)[Data$Drug]

所有这些情况,假设 'Drug' 中只有两个 unique 元素。


假设如果您在 'Drug' 中有 2 个以上的唯一元素,从代码中,在我看来,只有当 'Drug==2' 时,该值才应返回为 1。在 'Drug' 中创建另一个值

Data$Drug[4] <- 3

在这种情况下,我们可以更改 ifelse 条件,这样当 'Drug' 为 2 时返回 1,其他所有返回 0。

Data$Drug_factor <-  with(Data, ifelse(Drug==2, 1, 0))

一个类似的索引选项是,

Data$Drug_factor <- c(0,1)[(Data$Drug==2)+1]

数据

set.seed(24)
Data <- data.frame(Drug= sample(1:2, 10, replace=TRUE), val=rnorm(10))

【讨论】:

    【解决方案2】:

    这类问题有两种不同的类型。

    在简单的情况下,您希望将少量值更改为其他值。为此,我发现使用 plyr 中的mapvalues() 是一个很好的解决方案。例如:

    #lets pretend we have loaded some data where missing data is coded as 99
    set.seed(1) #reproducible results
    test_data = sample(c(0:5, 99), size = 1000, replace = T)
    #table of our dta
    table(test_data)
    

    输出:

    test_data
      0   1   2   3   4   5  99 
    138 145 150 150 127 142 148
    

    重新编码:

    #recode 99 to NA
    library(plyr)
    test_data_noNA = mapvalues(test_data, 99, NA)
    table(test_data_noNA, exclude = NULL) #also count NAs
    

    输出:

    test_data_noNA
       0    1    2    3    4    5 <NA> 
     138  145  150  150  127  142  148
    

    在另一种情况下,您希望有条件地将值更改为其他值,但它可能有大量/不确定/无限数量的值。

    例子:

    #continuous data
    set.seed(1) #reproducible results
    test_data = rnorm(1000) #normally distributed data
    hist(test_data) #plot with histogram
    

    但是,假设我们要处理离群值,我们将其定义为与平均值相差超过 2SD。但是,我们不只是想排除它们,因此我们将对它们进行重新编码。

    #change values above 2 to 2
    test_data[test_data > 2] = 2
    #change valuesbelow -2 to -2
    test_data[test_data < -2] = -2
    hist(test_data) #plot with histogram
    

    【讨论】:

      猜你喜欢
      • 2012-01-03
      • 2021-03-29
      • 2022-11-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-07-03
      • 1970-01-01
      相关资源
      最近更新 更多