Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
492 views
in Technique[技术] by (71.8m points)

r - Converting multiple boolean columns to single factor column

my data frame look like this:

      A S1 S2 S3 S4
1   ex1  1  0  0  0
2   ex2  0  1  0  0
3   ex3  0  0  1  0
4   ex4  1  0  0  0
5   ex5  0  0  0  1
6   ex6  0  1  0  0
7   ex7  1  0  0  0
8   ex8  0  1  0  0
9   ex9  0  0  1  0
10 ex10  1  0  0  0

i need to have it as a single factor list like:

A   Type
ex1 S1
ex2 S2
ex3 S3
ex4 S1
ex5 S4
ex6 S2
ex7 S1
ex8 S2
ex9 S3
ex10 S1

anybody help my problem?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can use apply and check the max in the columns 2-5 and then return the corresponding column name:

df$Type <- apply(df[2:5], 1, function(x) names(df)[which.max(x)+1] )

Afterwards, you can delete the columns you don't need anymore:

df <- df[,-c(2:5)]

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...