繁体   English   中英

查找行值等于零 (R) 的列索引(列名称)

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

我正在尝试在 dataframe“NA_perc_by_asset”中添加一个名为“Index”的列,该列带有一个字符串,该字符串是特定行(资产)等于零的所有列的串联。 1)第一个解决方案:

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

错误:1) 的结果似乎只是给了我 row = 到 0 的完全匹配

1) 的结果在这里您可以看到,对于每一行 function 只写 col“GLOBAL_ALL”,我想要其他 col 名称,其中 row = 0,例如 col“GLOBAL_HEAD”等。 使用 function round() 或者字符串/数字格式问题可能很重要。

桌子的样本在这里你可以看到一张桌子

或使用此代码: 2) 使用 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 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(":=").

请问有人可以为我提供解决方案吗?

多谢

基础 R 中的可能解决方案:

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

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

这使:

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

使用的示例数据:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM