使用条件替换另一行中特定行的值

时间:2018-07-02 14:43:56

标签: r

1)PatientID 2)Review_year 3)CurrentHealthstate  4)Healthstateprevious   

1   2005    2   NA
2   2006    3   NA
3   2007    3   NA
4   2008    3   NA
5   2009    3   NA
6   2010    3   NA
7   2011    3   NA
8   2012    3   NA
9   2013    3   NA

我想了解如何用上一个4)Healthstateprevious中的3)CurrentHealthstate的值替换2)Review_year中的NA值。

例如

1   2005    2   NIL
2   2006    4   2
3   2007    3   4
4   2008    2   3
5   2009    1   2
6   2010    3   1
7   2011    4   3
8   2012    5   4
9   2013    3   5

2 个答案:

答案 0 :(得分:0)

df <- read.table(text = "1   2005    2   NIL
2   2006    4   2
3   2007    3   4
4   2008    2   3
5   2009    1   2
6   2010    3   1
7   2011    4   3
8   2012    5   4
9   2013    3   5")

df %>% 
  mutate(newvar = lag(V3, 1))

  V1   V2 V3  V4 newvar
1  1 2005  2 NIL     NA
2  2 2006  4   2      2
3  3 2007  3   4      4
4  4 2008  2   3      3
5  5 2009  1   2      2
6  6 2010  3   1      1
7  7 2011  4   3      3
8  8 2012  5   4      4
9  9 2013  3   5      5

答案 1 :(得分:0)

一种实现此目的的方法是使用子集:

data$Healthstateprevious[-1] <- data$CurrentHealthstate[-ncol(data)]
data
  PatientID Review_year CurrentHealthstate Healthstateprevious
1         1        2005                  2                  NA
2         2        2006                  4                   2
3         3        2007                  3                   4
4         4        2008                  2                   3
5         5        2009                  1                   1
6         6        2010                  3                   3
7         7        2011                  4                   4
8         8        2012                  5                   5
9         9        2013                  3                   3

数据:

data <- data.frame(
  PatientID           = 1:9, 
  Review_year         = 2005:2013, 
  CurrentHealthstate  = c(2, 4, 3, 2, 1, 3, 4, 5, 3), 
  Healthstateprevious = NA
)