【问题标题】:Make a factor variable out of few data.frame columns从几个 data.frame 列中创建一个因子变量
【发布时间】:2017-10-17 18:04:53
【问题描述】:

我有一个data.frame,看起来像这样:

A <- data.frame(id = 1:5, col1 = c(0,1,1,0,0), col2 = c(2,0,0,0,0), col3 = c(0,0,0,3,3))

我如何用它创建一个factor 变量,所以它看起来像这样:

factor(c(2,1,1,3,3))

我知道如何从一列中提取一个因子,但不确定如何将它们合并在一起

【问题讨论】:

    标签: r dataframe


    【解决方案1】:

    您可以使用rowSums

    A <- data.frame(id = 1:5, col1 = c(0,1,1,0,0), col2 = c(2,0,0,0,0), col3 = c(0,0,0,3,3))
    A$col4 <- as.factor(rowSums(A[,2:4]))
    str(A)
    
    > str(A)
    'data.frame':   5 obs. of  5 variables:
      $ id  : int  1 2 3 4 5
    $ col1: num  0 1 1 0 0
    $ col2: num  2 0 0 0 0
    $ col3: num  0 0 0 3 3
    $ col4: Factor w/ 3 levels "1","2","3": 2 1 1 3 3
    

    【讨论】:

    • 谢谢!非常简单。我应该自己考虑rowSums
    【解决方案2】:

    您可以先将所有零转换为 NA,然后使用 coalescedplyr 将列“合并”为一个:

    library(dplyr)
    
    A$col4 = A %>%
      select(-id) %>%
      mutate_all(funs(replace(., . == 0, NA))) %>%
      {coalesce(!!! .)} %>%
      as.factor()
    

    结果:

      id col1 col2 col3 col4
    1  1    0    2    0    2
    2  2    1    0    0    1
    3  3    1    0    0    1
    4  4    0    0    3    3
    5  5    0    0    3    3
    
    > A$col4
    [1] 2 1 1 3 3
    Levels: 1 2 3
    

    注意: coalesce 中的!!! 表示法将参数拼接成点,所以它等价于coalesce(A$col1, A$col2, A$col3)

    【讨论】:

    • 嗨!看起来不错,但它给了我一个错误:Error in $&lt;-.data.frame(*tmp*, col4, value = c(NA, 1L, 1L, NA, NA, : replacement has 15 rows, data has 5
    猜你喜欢
    • 1970-01-01
    • 2020-04-12
    • 2012-12-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-26
    相关资源
    最近更新 更多