ZenMac
ZenMac

Reputation: 259

Add a column at the end of a data frame based on the column values in R

I have data frame as like this

structure(list(ID = c("A142867.12", "F134242.15", "H136244.11", 
"Y184937.13"), Name = c("BB", "PP", "II", "WW"), qusa = c(10.0341, 
12.7213, 0.157605, 0), nhg = c(24.7632, 50.562, 0.247947, 0.164736
), opk = c(26.931, 5.9474, 0.79539, 0)), class = "data.frame", row.names = c(NA, 
-4L))

I just need to add one more column (Result) with a tag (pass) if the values are more than or equal to 1.2, As like this

ID         Name qusa     nhg        opk    Result
A142867.12  BB  10.0341  24.7632    26.931  Pass
F134242.15  PP  12.7213  50.562     5.9474  Pass
H136244.11  II  0.157605 0.247947   0.79539  -
Y184937.13  WW  0        0.164736   0        -

Upvotes: 0

Views: 32

Answers (2)

TarJae
TarJae

Reputation: 78927

Or you can use case_when from dplyr package:

library(dplyr)

#your data
abc <- structure(list(ID = c("A142867.12", "F134242.15", "H136244.11", "Y184937.13"), 
               Name = c("BB", "PP", "II", "WW"), 
               qusa = c(10.0341, 12.7213, 0.157605, 0), 
               nhg = c(24.7632, 50.562, 0.247947, 0.164736), 
               opk = c(26.931, 5.9474, 0.79539, 0)), 
          class = "data.frame", row.names = c(NA, -4L))

# case_when
abc <- abc %>% 
  mutate(Results = case_when(qusa >= 1.2 | nhg >= 1.2 | opk >= 1.2 ~ "pass",
                             TRUE ~ "-"))
# View dataframe
View(abc)

Upvotes: 1

Ronak Shah
Ronak Shah

Reputation: 388982

You can assign 'Pass' if all the numeric columns in the dataframe are greater than equal to 1.2.

cols <- sapply(df, is.numeric)
df$result <- ifelse(rowSums(df[cols] < 1.2) == 0, 'Pass', '-')
#Without ifelse
#df$result <- c('-', 'Pass')[(rowSums(df[cols] < 1.2) == 0) + 1]
df

#          ID Name      qusa       nhg      opk result
#1 A142867.12   BB 10.034100 24.763200 26.93100   Pass
#2 F134242.15   PP 12.721300 50.562000  5.94740   Pass
#3 H136244.11   II  0.157605  0.247947  0.79539      -
#4 Y184937.13   WW  0.000000  0.164736  0.00000      -

Upvotes: 1

Related Questions