R - How to make a subset of columns based on values in a row in a data frame

主宰稳场 提交于 2019-12-04 00:44:02

Your data is nor arranged in a good way. It would be better to reshape it.

In absence of input data this is just a guess:

df <- data.frame(MarkerID=c("Class","A123","A124"),
                 MarkerName=c("","X","Y"),
                 Patient.1=c(0,1,5),
                 Patent.2=c(1,2,6),
                 Patent.3=c(0,3,7),
                 Patient.4=c(1,4,8))

#  MarkerID MarkerName Patient.1 Patent.2 Patent.3 Patient.4
#1    Class                    0        1        0         1
#2     A123          X         1        2        3         4
#3     A124          Y         5        6        7         8

df[,c(TRUE,TRUE,df[1,-(1:2)]==0)]

#  MarkerID MarkerName Patient.1 Patent.3
#1    Class                    0        0
#2     A123          X         1        3
#3     A124          Y         5        7

Here c(TRUE,TRUE,df[1,-(1:2)]==0) creates a logical vector, which is TRUE for the first two columns and for those columns, which have a 0 in the first row. Then I subset the columns based on this vector.

df[,c(TRUE,TRUE,df[1,-(1:2)]==1)]

#  MarkerID MarkerName Patent.2 Patient.4
#1    Class                   1         1
#2     A123          X        2         4
#3     A124          Y        6         8

This would reshape your data into a more common format (for statistical software):

library(reshape2)  
df2 <- merge(melt(df[1,],variable.name="Patient",value.name="class")[-(1:2)],
             melt(df[-1,],variable.name="Patient"),all=TRUE)

#    Patient class MarkerID MarkerName value
#1  Patent.2     1     A123          X     2
#2  Patent.2     1     A124          Y     6
#3  Patent.3     0     A123          X     3
#4  Patent.3     0     A124          Y     7
#5 Patient.1     0     A123          X     1
#6 Patient.1     0     A124          Y     5
#7 Patient.4     1     A123          X     4
#8 Patient.4     1     A124          Y     8

You could then use subset:

subset(df2,class==0)

#    Patient class MarkerID MarkerName value
#3  Patent.3     0     A123          X     3
#4  Patent.3     0     A124          Y     7
#5 Patient.1     0     A123          X     1
#6 Patient.1     0     A124          Y     5
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!