jer*_*ord 12 r subset dataframe
我有一个矩阵,我想分组并最终用于制作情节.该数据是群体中每个患者的特定血液标记物的计数列表.它看起来像这样:
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))
Run Code Online (Sandbox Code Playgroud)
我想建立所有患者(第3-6列)的数据框,其类值为零(第1行),所有患者的第二个数据框的类值为1.
在过去,我使用子集函数根据列中的值选择行,是否可以根据行中的值选择列的子集?
我试过这个:
x <- subset(data, data[1,] == 0)
Run Code Online (Sandbox Code Playgroud)
但是,当我这样做时dim(x),列数相同dim(data)但行数不同.有关如何使其返回的任何想法只返回第1行中值为0的列?
罗兰,是的.你的例子是df是数据框的样子.数据框中有大约30,000个标记和> 400个患者,因此我没有发布dput(head(data)).感谢重塑小费,我会试一试.
您的示例代码确实可以根据行对列进行子集化
data[,c(TRUE,TRUE,data[1,-(1:2)]==1)]
Run Code Online (Sandbox Code Playgroud)
在数据上我然后能够获得包含所有行的数据框,并且只能获得具有指示类的列.
Rol*_*and 12
您的数据也没有很好的安排.重塑它会更好.
如果没有输入数据,这只是一个猜测:
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
Run Code Online (Sandbox Code Playgroud)
这里c(TRUE,TRUE,df[1,-(1:2)]==0)创建一个逻辑向量,TRUE用于前两列和那些在第一行中为0的列.然后我根据这个向量对列进行子集化.
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
Run Code Online (Sandbox Code Playgroud)
这会将您的数据重塑为更常见的格式(对于统计软件):
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
Run Code Online (Sandbox Code Playgroud)
然后你可以使用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
Run Code Online (Sandbox Code Playgroud)