简体   繁体   中英

Creating a new column based on other columns in a dataframe R

I have a dataframe that looks like this:

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

I want to create a new column that has a value of 1 if at least one of the values in the row is greater or equal to 8 and a value of 0 if all of the values in the row are less than 8. So the final result would look something like this:

> 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

Thanks!

This works:

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

Using 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

Alternatively using matrix multiplication

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM