获取dat等于的列名 [英] Get column names where dat is equal to
本文介绍了获取dat等于的列名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个包含7行4列的数据帧(df)(分别命名为c1,c2,c3,c4):
I have a data frame (df) with 7 rows and 4 columns (named c1, c2, c3, c4):
c1 c2 c3 c4
Yes No Yes No
Yes Yes No No
No Yes No No
Yes No No No
Yes No Yes No
Yes No No No
No No Yes No
如果第1到第4列的值等于是",我想向数据框添加第5列,名为预期结果".例如,在第1行上,第1列和第3列具有是"参数.要填充预期结果"列,我将进行连接并将Column1名称和Column 2名称添加到结果中.
I want to add a 5th column to the data frame named Expected Result if the values on columns 1 to 4 are equal to "Yes". For example, on row 1, I have "Yes" parameters in Column 1 and Column 3. To populate Expected Result column, I would concatenate and add Column1 name and Column 2 name to the result.
以下是预期的完整结果:
Here is the full results expected:
c1, c3
c1, c2
c2
c1
c1, c3
c1
c3
我有以下代码行,但是有些不正确:
I have the following line of code but something is not quite right:
df$Expected_Result <- colnames(df)[apply(df,1,which(LETTERS="Unfit"))]
推荐答案
使用 data.table
library(data.table)
setDT(df)[, rownum:=1:.N,]
df$Expected_result <- melt(df, "rownum")[,
toString(variable[value=="Yes"]), rownum]$V1
这篇关于获取dat等于的列名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文