如何根据特定条件替换dataframe列中的值

时间:2016-11-29 14:52:00

标签: r

我有以下数据框u

   u<- data.frame(a=c("x1","x2","x3","x4","x5","x6","x7"),b=c(2005,2006,2007,2008,2009,2010,2011),c1=c(0.5,0.5,0.5,0.6,0.7,0.9,0.5),c2=c(0.5,0.5,0.5,0.6,0.7,0.9,0.5),c3=c(0.5,0.5,0.5,0.6,0.7,0.9,0.5))
a   b       c1  c2  c3
x1  2005    0.5 0.5 0.5
x2  2006    0.5 0.5 0.5
x3  2007    0.5 0.5 0.5
x4  2008    0.6 0.6 0.6
x5  2009    0.7 0.7 0.7
x6  2010    0.9 0.9 0.9
x7  2011    0.5 0.5 0.5

我想根据b列中的值替换列(c1,c2,c3)中的值。因此,如果列b中的值小于2008,则将列(c1,c2,c3)中的值替换为1,2和3.结果数据框为

 a  b     c1    c2  c3
x1  2005    1   2   3
x2  2006    1   2   3
x3  2007    1   2   3
x4  2008    0.6 0.6 0.6
x5  2009    0.7 0.7 0.7
x6  2010    0.9 0.9 0.9
x7  2011    0.5 0.5 0.5

4 个答案:

答案 0 :(得分:1)

不使用库,或者如果您需要将其概括为多个c列,您可以执行以下操作:

u <- data.frame(a=c("x1","x2","x3","x4","x5","x6","x7"),
b=c(2005,2006,2007,2008,2009,2010,2011),
c1=c(0.5,0.5,0.5,0.6,0.7,0.9,0.5),
c2=c(0.5,0.5,0.5,0.6,0.7,0.9,0.5),
c3=c(0.5,0.5,0.5,0.6,0.7,0.9,0.5))

然后将普通括号表示法用于子集,并一次分配三列:

u[u$b<2008,3:5] <- data.frame(1,2,3)
u
   a    b  c1  c2  c3
1 x1 2005 1.0 2.0 3.0
2 x2 2006 1.0 2.0 3.0
3 x3 2007 1.0 2.0 3.0
4 x4 2008 0.6 0.6 0.6
5 x5 2009 0.7 0.7 0.7
6 x6 2010 0.9 0.9 0.9
7 x7 2011 0.5 0.5 0.5

答案 1 :(得分:0)

试试这个

library(magrittr)

u$c1 %<>% ifelse(u$b < 2008, 1, .)

u$c2 %<>% ifelse(u$b < 2008, 2, .)

u$c3 %<>% ifelse(u$b < 2008, 3, .)

答案 2 :(得分:0)

我碰巧发现这更直观,但只是偏好。

u$c1[u$b < 2008] <- 1 u$c2[u$b < 2008] <- 2 u$c3[u$b < 2008] <- 3

答案 3 :(得分:0)

另一种方式......

library(dplyr)
u %>%
  mutate(c1 = ifelse(b < 2008, 1, c1),
         c2 = ifelse(b < 2008, 2, c2),
         c3 = ifelse(b < 2008, 3, c3)
        )