首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在R中构造这个二进制变量?

如何在R中构造这个二进制变量?
EN

Stack Overflow用户
提问于 2014-11-13 20:22:22
回答 4查看 184关注 0票数 5

目的是检查索引i处的值是否为1,然后将前六个条目设为1。

代码语言:javascript
复制
x <- c(0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1)

## Required output 
y <- c(1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1)

## Attempt 
for(j in seq_along(x)){
if(x[j] == 1){
   for(i in (j-6):j)
   x[i] = 1
   }}

你能帮助解决这个问题或更好的方法吗?

谢谢。

EN

回答 4

Stack Overflow用户

发布于 2014-11-13 20:40:03

您可以尝试以下选项(但不要忘记在尝试每个选项时初始化x,因为我正在覆盖它)

代码语言:javascript
复制
indx <- mapply(function(x, y) x:y, which(x == 1) - 6 , which(x == 1))
x[indx[indx > 0]] <- 1
x
## [1] 1 1 1 1 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1

或者更简单

代码语言:javascript
复制
indx <- sapply(which(x == 1) - 6, function(x) x:(x + 6))
x[indx[indx > 0]] <- 1
x
## [1] 1 1 1 1 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1

代码语言:javascript
复制
indx <- apply(cbind(which(x == 1) - 6 , which(x == 1)), 1, function(x) x[1]:x[2])
x[indx[indx > 0]] <- 1
x
## [1] 1 1 1 1 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1

代码语言:javascript
复制
indx <- seq_len(6)
indx <- sapply(which(x == 1), function(x) x - indx)
x[indx[indx > 0]] <- 1
x
## [1] 1 1 1 1 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1
票数 5
EN

Stack Overflow用户

发布于 2014-11-13 20:43:11

使用filter的完全矢量化的解决方案

代码语言:javascript
复制
as.integer( #turn logical value into numbers
  as.logical( #coerce to logical --> 0 becomes FALSE, everything else TRUE
   rev( #reverse order
    filter( #linear filtering
      c(rep(0, 6), #pad with zeros in the beginning to avoid NAs
        rev(x)), #revers order of input vector
          c(rep(1, 7)), sides=1 #y_i = x_i * 1 + x_(i-1) * 1 +...+ x_(i-6) * 1 
  )[-(1:6)]))) #remove NA values

#[1] 1 1 1 1 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1
票数 5
EN

Stack Overflow用户

发布于 2014-11-13 20:32:10

使用'for‘循环:

代码语言:javascript
复制
ddf = data.frame(x,y=0)
for(i in 1:nrow(ddf)){
    if(ddf[i,'x']==1){
        j = i-5
        if(j<1) j=1
        ddf[j:i,'y'] = 1
    }
}
ddf
   x y
1  0 1
2  0 1
3  0 1
4  1 1
5  0 0
6  0 0
7  0 0
8  0 0
9  0 0
10 0 0
11 0 0
12 0 1
13 0 1
14 0 1
15 0 1
16 0 1
17 1 1
18 0 1
19 1 1

y = ddf$y
y
 [1] 1 1 1 1 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/26908804

复制
相关文章

相似问题

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