【问题标题】:R - adding a value to a new row if column name matches a stringR - 如果列名与字符串匹配,则将值添加到新行
【发布时间】:2021-11-17 14:26:54
【问题描述】:

我有一个非常大的data.table,结构如下:

variant ID1 ID2 ID3 ID4 .... ID80000
123     0    1   2   1         0
321     1    2   1   1         1
543     1    1   2   1         1
6542    1    0   0   1         0  
243     1    0   2   1         1
654     0    1   1   2         1 
342     1    2   1   2         1

我想根据字符串中的 ID 是否存在于上表中添加一个 0 或 1 的行。

假设我有一个列表: a

期望的输出是:

variant ID1 ID2 ID3 ID4 .... ID80000
123     0    1   2   1         0
321     1    2   1   1         1
543     1    1   2   1         1
6542    1    0   0   1         0  
243     1    0   2   1         1
654     0    1   1   2         1 
342     1    2   1   2         1
present 0    1   0   1         0

有点像这个问题,但排成一行:Create new conditional column if string contains elements from list

我试过了:

df$present <- colnames(df) %in% id_list 

但我收到一个错误,因为它说行太多。

非常感谢您的帮助

ifelse 在这里有用吗?

【问题讨论】:

  • df$present &lt;- 创建一个新的。看起来你想要一个新的 rowrbinddf['present', ] &lt;- 想到添加一行。
  • 感谢您发现巨大的失败!

标签: r dataframe


【解决方案1】:

我创建了一个与您的 df 类似的结构,并将一行附加到数据框。

df <- data.frame(matrix(ncol=10, nrow=0)) 
colnames(df) <- c("variant", rep(paste0("ID",2:ncol(df))))
a <- c("ID42", "ID4")
df[nrow(df) + 1,] <- c("present", ifelse(colnames(df) %in% a, 1, 0)[-1])
df

variant ID2 ID3 ID4 ID5 ID6 ID7 ID8 ID9 ID10
present   0   0   1   0   0   0   0   0    0

【讨论】:

    【解决方案2】:

    感谢上面的@sashahafner:

    I got df['present',] <-colnames(df) %in% id_list  
    

    工作,不确定这是最好的解决方案,但是嘿嘿!

    【讨论】:

    • 嗨@tacrolimus。不知道这是否重要,但您的解决方案导致“存在”为rowname。但是在您的问题中指出的所需结果“现在”在variant 列中......
    • 感谢您抽出宝贵时间查看。是的,这就是我所希望的!
    • 好的。如果你得到了你希望的结果,那么一切都很好。干杯。
    猜你喜欢
    • 2015-12-02
    • 2020-07-22
    • 1970-01-01
    • 1970-01-01
    • 2022-01-15
    • 2018-12-05
    • 2022-07-06
    • 2022-10-15
    • 2021-12-28
    相关资源
    最近更新 更多