首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何在R中建立多重假设条件?

如何在R中建立多重假设条件?
EN

Stack Overflow用户
提问于 2019-01-28 18:35:56
回答 3查看 52关注 0票数 1

我有一个叫做dft的数据。我想添加Ch1..。Ch4作为chr列在dft中。如果我还有其他条件的话,但它似乎不起作用。下面我的if语句有什么问题?

代码语言:javascript
运行
复制
dft <- structure(list(pos_coverage = c(0, 0, 0, 0, 0, 0, 0, 0, 0, 0), 
    position = 1:10, neg_coverage = c(0, 0, 0, 0, 0, 0, 0, 0, 
    0, 0)), .Names = c("pos_coverage", "position", "neg_coverage"
), row.names = c(NA, 10L), class = "data.frame")


Ch1 <- 1:2
Ch2 <- 3:5
Ch3 <- 6:8
Ch4 <- 9:10

if( dft$position == Ch1){
  dft$chr <- "Ch1"
} else if (dft$position == Ch2){
  dft$chr <- "Ch2"
} else if (dft$position == Ch3){
  dft$chr <- "Ch3"
} else {dft$chr <- "Ch4"}
EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2019-01-28 18:39:33

一个更好的选择是使用stack创建键/val数据,然后执行连接

代码语言:javascript
运行
复制
library(tidyverse)
stack(mget(paste0("Ch", 1:4))) %>% 
   right_join(dft, by = c("values" = "position")) %>%
   rename(chr = ind)
#   values chr pos_coverage neg_coverage
#1       1 Ch1            0            0
#2       2 Ch1            0            0
#3       3 Ch2            0            0
#4       4 Ch2            0            0
#5       5 Ch2            0            0
#6       6 Ch3            0            0
#7       7 Ch3            0            0
#8       8 Ch3            0            0
#9       9 Ch4            0            0
#10     10 Ch4            0            0
票数 3
EN

Stack Overflow用户

发布于 2019-01-28 18:41:05

考虑嵌套ifelse并将==更改为%in%

代码语言:javascript
运行
复制
dft$chr <- with(dft, ifelse(position %in% Ch1, "Ch1", 
                           ifelse(position %in% Ch2, "Ch2",
                                  ifelse(position %in% Ch3, "Ch3", "Ch4")
                                 )
                           )
               )

Rextester演示

票数 5
EN

Stack Overflow用户

发布于 2019-01-28 19:06:59

为了避免ifelse(),您可以考虑数据的子集。

代码语言:javascript
运行
复制
dft$chr <- NA
dft$chr[dft$position %in% Ch1] <- "Ch1"
dft$chr[dft$position %in% Ch2] <- "Ch2"
dft$chr[dft$position %in% Ch3] <- "Ch3"
dft$chr[dft$position %in% Ch4] <- "Ch4"

有了一个lapply()和一个测试集,我们就可以将其自动化。

代码语言:javascript
运行
复制
test.set <- ls(pattern="Ch")
# # or
# test.set <- paste0("Ch", 1:4)

l <- lapply(test.set, function(x) {
  sub <- dft$position %in% get(x)
  dft$chr[sub] <- x
  dft[sub, ]
  })

结果

代码语言:javascript
运行
复制
> do.call(rbind, l)
   pos_coverage position neg_coverage chr
1             0        1            0 Ch1
2             0        2            0 Ch1
3             0        3            0 Ch2
4             0        4            0 Ch2
6             0        6            0 Ch3
7             0        7            0 Ch3
8             0        8            0 Ch3
9             0        9            0 Ch4
10            0       10            0 Ch4
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/54408257

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档