R - 获取dat等于的列名 [英] R - get column names where dat is equal to
问题描述
全部
我有一个数据框(df),其中有7行和4列(命名为c1,c2,c3,c4):
c1 c2 c3 c4
是否是否
是是否否
否是否否
是否否否
是否是否
是否否否
否否是否
我想如果第1列至第4列的值等于是,则将第5列添加到名为预期结果的数据框中。例如,在第1行,我在第1列和第3列中有是参数。要填充预期结果列,我将连接并添加Column1名称和列2名称到结果。
以下是预期的完整结果:
c1,c3
c1,c2
c2
c1
c1,c3
c1
c3
我有以下代码行,但有些不太正确:
df $ Expected_Result< - colnames(df )[apply(df,1,which(LETTERS =Unfit))]
非常感谢。
您可以尝试以下方式:
colnames(df)< - c(c1,c2,c3,c4)
/ pre>
test< - (apply ,1,function(x)which(x ==Yes)))
df $ cols< - lapply(test,names)
这是你最初尝试的想法。
要整理输出,您可以:
df $ cols< - gsub(c(, ,df $ cols,fixed = TRUE)
df $ cols< - gsub(),,df $ cols,fixed = TRUE)
这将删除
c()
。All, 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
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"))]
Any help would be much appreciated.
解决方案You could try something like:
colnames(df) <- c("c1", "c2", "c3", "c4") test <- (apply(df,1,function(x) which(x=="Yes"))) df$cols <- lapply(test,names)
This was along the lines of what you were initially trying I think.
To tidy the output you could:
df$cols <- gsub("c(", "", df$cols, fixed = TRUE) df$cols <- gsub(")", "", df$cols, fixed = TRUE)
This removes the
c()
.这篇关于R - 获取dat等于的列名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!