【问题标题】:Creating a factor from a numeric column vector in R从 R 中的数值列向量创建一个因子
【发布时间】:2020-02-26 12:12:45
【问题描述】:

我在 df 中有一个权重数字列 (df$weight0)。我想根据df$weight0 中的值创建一个新列df$weight1,它是factor。

如果df$weight0中的值小于或等于170,则df$weight1中的对应值应为1,但如果df$weight0中的值大于170,则df$weight1中的对应值应为2.

下面的代码是我尝试过的,但它给出的是单个值而不是向量。

  if (i<=170){
    i==1
  }else{
    i==2
  }
}

【问题讨论】:

  • df$weight1 &lt;- (df$weight0&gt;170)+1

标签: dataframe r dataframe for-loop factors


【解决方案1】:

ifelse 可以使用矢量化输入:

df$weight1 <- ifelse(df$weight0<=170,1,2)

【讨论】:

    【解决方案2】:

    您正在检查 i 的值,而不是 df 中的值。您的新列的分配也没有实现。请尝试以下操作。

    for (i in wcgs$weight0){
      if (wcgs$weight0[i]<=170){
        wcgs$weight1[i] <- 1
      }else{
        wcgs$weight1[i] <- 2
      }
    }
    

    【讨论】:

    • 谢谢。所以我使用 wcgs$weight1[i] 来更改该索引处的值
    【解决方案3】:

    使用cut()按区间离散化连续变量

    对于这种区间分类,有一个非常有用的函数cut。

    nums <- nums <- runif(100, min=0, max=300) # n = 100 random numbers between 0 and 300
    factorized_num <- cut(nums, c(-Inf, 170, +Inf))
    # you can name the categories as you want:
    levels(factorized_num) <- c(1, 2) # first interval 1, next interval 2
    # with include.lowest=TRUE or FALSE you can determine whether lower limit is <= or <
    

    或者使用Vectorize()对非向量化函数进行向量化

    # define for one case:
    categorize <- function(i) if (i<=170) 1 else 2
    # then vectorize it:
    categorize <- Vectorize(categorize)
    

    现在你可以使用它了:

    categories <- categorize(nums)
    head(categories) ## 1 2 1 1 ...
    

    我更喜欢这个——根据我的经验——比ifelse() 更喜欢这个,因为你可以完全控制单个案例。

    【讨论】:

    • 谢谢大家。我尝试了 cut 方法wcgs$w8t&lt;-cut(wcgs$weight0,breaks = c(78,170,320), labels = c("&lt;= 170 lbs", "&gt; 170 lbs"), include.lowest=T)
    • 不错!最好的办法是包含/命名所有限制(如果没有限制,-Inf 和 +Inf 会很有用)。
    【解决方案4】:

    使用包中的case_when :

    library(dplyr)
    df %>% mutate(df$weight1 = case_when(df$weight0 =< 170 ~ 1,
                                         df$weight0 > 170 ~ 2)) 
    

    case_when() 帮助制定if-else 构造,mutate() 修改或添加列。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-05-21
      • 1970-01-01
      • 2020-11-19
      • 2020-11-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多