简体   繁体   中英

Add a column of values based on two other columns in R

我正在尝试向表中添加一列,其中名为“ID”的新列将包含 3-5 或 3.5 或 3/5,如果第 1 列包含值 3,第 2 列包含值 5。

library(dplyr)
data %>% mutate(ID = paste0(column1,'-',column2))

you can change - with any symbol you want.

As noted by others, an ifelse operation will be helpful:

Toy data:

df <- data.frame(
  c1 = c(1,3,4,2,6,3,5),
  c2 = c(2,5,3,0,2,5,5)
)

df$ID <- ifelse(df$c1 == 3 & df$c2 == 5,        # condition to meet
                paste(df$c1, df$c2, sep = "/"), # action if condition == TRUE
                NA)                             # action if condition == FALSE

Result:

df
  c1 c2   ID
1  1  2 <NA>
2  3  5  3/5
3  4  3 <NA>
4  2  0 <NA>
5  6  2 <NA>
6  3  5  3/5
7  5  5 <NA>

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