Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/66.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何根据R中的条件填充数据帧_R_Dataframe - Fatal编程技术网

如何根据R中的条件填充数据帧

如何根据R中的条件填充数据帧,r,dataframe,R,Dataframe,我创建了一个像这样的空数据框 id Alyr Crub Lala Brap Bole Spar Esal Aara Thas 1 XLOC_003940_TBH_1 NA NA NA NA NA NA NA NA NA id Alyr Crub Lala Brap Bole Spar Esal Aara Thas 1 XLOC_003940_T

我创建了一个像这样的空数据框

                 id Alyr Crub Lala Brap Bole Spar Esal Aara Thas
1 XLOC_003940_TBH_1   NA   NA   NA   NA   NA   NA   NA   NA   NA
                 id        Alyr                  Crub Lala Brap Bole Spar Esal Aara Thas
1 XLOC_003940_TBH_1   Ortholog_Known_Gene_Sense   NF   NF   NF   NF   NF   NF   NF   NF
我想看看
id
和列名是否匹配,然后它应该用特定的值替换“NA”。以下是一个例子:

ex1 <- "Alyr_XLOC_003940_TBH_1_Ortholog_Known_Gene_Sense"

sp <- sub("([A-Za-z]+)_(XLOC_\\d+_TBH_1)_([A-Za-z_]+)","\\1", ex1)
gene <- sub("([A-Za-z]+)_(XLOC_\\d+_TBH_1)_([A-Za-z_]+)","\\2", ex1)
fun <- sub("([A-Za-z]+)_(XLOC_\\d+_TBH_1)_([A-Za-z_]+)","\\3", ex1)
我被困在这里,不知道该怎么做?

使用矩阵子集:

df1$id <- gene
df1[cbind(1:nrow(df1), match(sp, names(df1)))] <- fun

df1$id感谢它的工作。我刚刚添加了这个
df1[is.na(df1)]
##Example
nms <- scan(what="character", text="id Alyr Crub Lala Brap Bole Spar Esal Aara Thas")
df1 <- as.data.frame(matrix(NA, 3, 10))
names(df1) <- nms
df1
#  id Alyr Crub Lala Brap Bole Spar Esal Aara Thas
#1 NA   NA   NA   NA   NA   NA   NA   NA   NA   NA
#2 NA   NA   NA   NA   NA   NA   NA   NA   NA   NA
#3 NA   NA   NA   NA   NA   NA   NA   NA   NA   NA


ex1 <- c("Alyr_XLOC_003940_TBH_1_Ortholog_Gene",
         "Lala_XLOC_1234_TBH_1_Lalala_Gene",
         "Thas_XLOC_5678_TBH_1_Thasthas_Gene")

sp <- sub("([A-Za-z]+)_(XLOC_\\d+_TBH_1)_([A-Za-z_]+)","\\1", ex1)
gene <- sub("([A-Za-z]+)_(XLOC_\\d+_TBH_1)_([A-Za-z_]+)","\\2", ex1)
fun <- sub("([A-Za-z]+)_(XLOC_\\d+_TBH_1)_([A-Za-z_]+)","\\3", ex1)

df1$id <- gene
df1[cbind(1:nrow(df1), match(sp, names(df1)))] <- fun
df1
  #                  id          Alyr Crub        Lala Brap Bole Spar Esal Aara          Thas
  # 1 XLOC_003940_TBH_1 Ortholog_Gene   NA        <NA>   NA   NA   NA   NA   NA          <NA>
  # 2   XLOC_1234_TBH_1          <NA>   NA Lalala_Gene   NA   NA   NA   NA   NA          <NA>
  # 3   XLOC_5678_TBH_1          <NA>   NA        <NA>   NA   NA   NA   NA   NA Thasthas_Gene