简体   繁体   中英

Find column index (col names) where row value is equal to zero (R)

I am trying to add a column called "Index" in the dataframe "NA_perc_by_asset" with a string that is the concatenation of all columns for which a specific row (asset) is equal to zero. 1) First solution:

NA_perc_by_asset$Index=apply(NA_perc_by_asset, 1, function(i) paste(names(i[i == 0 ]), collapse = ', '))

Error: The results of 1) seems to just give me the exact match of row = to 0

result of 1) here you can see that for each row the function write just the col "GLOBAL_ALL" and I would like other col names for which row =0, for instance col "GLOBAL_HEAD" and others. Maybe is matter to use the function round() or is matter of string/numeric formatting issues.

sample of the table here you can see a piece of table

Or with this code: 2) Using paste():

NA_perc_by_asset$Index2=NA_perc_by_asset[ , paste_column  := paste( names( 
NA_perc_by_asset[,colMeans(NA_perc_by_asset==0)==T] ), collapse = ', ') ]

Error:

Error in `:=`(paste_column, paste(names(NA_perc_by_asset[, colMeans(NA_perc_by_asset ==  : 
Check that is.data.table(DT) == TRUE. Otherwise, := and `:=`(...) are defined for use in j, 
once only and in particular ways. See help(":=").

Please someone can provide me a solution?

thanks a lot

A possible solution in base R:

ci <- col(df)[df == 0]
ri <- row(df)[df == 0]
ta <- tapply(names(df)[ci], ri, FUN = toString)

df[names(ta), "index"] <- ta

which gives:

 > df xy index 1 1 2 <NA> 2 0 3 x 3 2 0 y 4 0 0 x, y

Used example data:

df <- data.frame(x = c(1,0,2,0), y = c(2,3,0,0))

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