【问题标题】:Creating a new column based on other columns in a dataframe R基于数据框 R 中的其他列创建新列
【发布时间】:2020-05-05 22:42:36
【问题描述】:

我有一个如下所示的数据框:

df <- data.frame('col1'=c(1,2,2,4,5), 'col2'=c(4,9,3,5,13), 'col3'=c(3,5,8,7,10))
> df
  col1 col2 col3
1    1    4    3
2    2    9    5
3    2    3    8
4    4    5    7
5    5   13   10

如果行中至少一个值大于或等于 8,我想创建一个值为 1 的新列,如果 all 行中的值小于 8。因此最终结果将如下所示:

> df
  col1 col2 col3  new
1    1    4    3    0 
2    2    9    5    1
3    2    3    8    1
4    4    5    7    0
5    5   13   10    1

谢谢!

【问题讨论】:

标签: r


【解决方案1】:

这行得通:

df$new <- apply(df, 1, function(x) max(x >= 8))
df
#   col1 col2 col3 new
# 1    1    4    3   0
# 2    2    9    5   1
# 3    2    3    8   1
# 4    4    5    7   0
# 5    5   13   10   1

【讨论】:

    【解决方案2】:

    使用rowSums

    df$new <- +(rowSums(df>=8, na.rm=TRUE) > 0); df
      col1 col2 col3 new
    1    1    4    3   0
    2    2    9    5   1
    3    2    3    8   1
    4    4    5    7   0
    5    5   13   10   1
    

    【讨论】:

      【解决方案3】:

      或者使用矩阵乘法

      df$new <- as.numeric(((df >= 8) %*% rep(1, ncol(df))) > 0)
      df
        col1 col2 col3 new
      1    1    4    3   0
      2    2    9    5   1
      3    2    3    8   1
      4    4    5    7   0
      5    5   13   10   1
      
      # Or logical column
      df$new <- ((df >= 8) %*% rep(1, ncol(df))) > 0
      df
        col1 col2 col3   new
      1    1    4    3 FALSE
      2    2    9    5  TRUE
      3    2    3    8  TRUE
      4    4    5    7 FALSE
      5    5   13   10  TRUE
      

      【讨论】:

        猜你喜欢
        • 2022-01-25
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-10-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多