简体   繁体   中英

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

I have a dataframe with 144 columns with lots of NAs, I want to create new column with dichotomous value based on current columns. So that, if columns 1: 126 have values the new column get "Q" and if columns 126:144 have values the new column get "R". In the case that there are values for both (1:126 & 126:144), it will get "R" too. If non has value the new column get "NA".

Ok, let's say your data.frame is called df, using below as an example:

df = data.frame(matrix(runif(144*100),ncol=144))
df[df < 0.99] = NA

Then you can do:

df$new_column = NA
df$new_column[rowSums(!is.na(df[,1:126]))>0] = "Q"
df$new_column[rowSums(!is.na(df[,126:144]))>0] = "R"

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