首页 > 解决方案 > 将数据框的感兴趣框合并到同一列中

问题描述

我是 R 的初学者。对于我的实习,我需要为我的数据框的每一行的唯一非 NA 值创建一个新列。问题是这个值并不总是在同一列上。

我正在编辑我的帖子。这是我的代码

wd<-getwd()
datapath<-paste0(wd,"/data/HSgeneAges.tab")
feat<-read.table(datapath,sep='\t',header = TRUE)
feat<-data.frame(feat[,c(2,3,4,9)])
#creating a dataframe of 18 columns 
#with colnames to be each unique value of column 4 of  feat dataframe
geneage<-data.frame(matrix(ncol=18,nrow=0))
nomcol<-unique(feat[,4])
colnames(geneage)<-nomcol

for (i in 1:length(feat[,4])){  # as many rows as in feat
  for (j in 1:length(nomcol)){  # length is 18 ( number of columns of geneage)
    if (feat[i,4]==nomcol[j]){
      geneage[i,j]<-j
    }
  }
}
#binding geneage and feat on commons columns 
#and removing that column than make a file out of it
geneage<-cbind(feat,geneage)
geneage<-geneage[,-4]
datapath<-paste0(wd,"/data/p.txt")
write.table(geneage,datapath)

这是到目前为止代码产生的内容(我无法向您展示所有行 (21),因为行数太多)

这是我想要的(前 11 行的示例)

dput(df)
structure(list(Chromosome = c("X", "X", "20", "1", "1", "1", 
"1", "6", "6", "6", "1"), Start = c(99883667L, 99839799L, 49551404L, 
169818772L, 169631245L, 27938575L, 196621008L, 143815948L, 53362139L, 
41040684L, 24683489L), End = c(99894988L, 99854882L, 49575092L, 
169863408L, 169823221L, 27961788L, 196716634L, 143832827L, 53481768L, 
41067715L, 24743424L), geneage = c(1, 1, 2, 3, 1, 1, 4, 1, 2, 
2, 5)), class = "data.frame", row.names = c(NA, 11L))

我希望现在更清楚。

顺便说一句,如果有人知道要避免我急于知道的循环!亚历克西斯。

标签: rdataframe

解决方案


推荐阅读