简体   繁体   中英

Create a new column in a dataframe

Say I have a dataframe

group<-c("NA","HIGH","LOW","NA","HIGH")
a<-c(14,16,21,34,45)
dataset<-data.frame(group,a)

I would like to create a new column called "a_high". If "group" is high I would like the corresponding value for "a" to be returned in "a_high". If "group" is "low" or "NA" I would like "NA" to be returned in "a_high". I hope this makes sense.

Here you go:

dataset$a_high <- ifelse(dataset$group == 'HIGH', dataset$a, NA)

Output:

 > dataset group a a_high 1 NA 14 NA 2 HIGH 16 16 3 LOW 21 NA 4 NA 34 NA 5 HIGH 45 45 

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