根据数据框R中的其他列创建新列

时间:2020-05-05 22:42:36

标签: r

我有一个看起来像这样的数据框:

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 <,则值为0 / strong>该行中的值小于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

谢谢!

3 个答案:

答案 0 :(得分: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

答案 1 :(得分:1)

使用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

答案 2 :(得分:0)

或者使用矩阵乘法

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