在R中替换了列

时间:2017-10-11 03:44:06

标签: r

我有以下data.frame,

dt2017 <- data.frame(id=LETTERS[1:4],year=2017,city1=c(0,1,0,1),city2=c(0,0,1,0),
                     city3=c(1,0,1,0),city4=c(0,0,0,0))

dt2017
   id year city1 city2 city3 city4
1:  A 2017     0     0     1     0
2:  B 2017     1     0     0     0
3:  C 2017     0     1     1     0
4:  D 2017     1     0     0     0

现在,我希望最终结果如下:

   id year city1 city2 city3 city4
1:  A 2017     0     0     A     0
2:  B 2017     B     0     0     0
3:  C 2017     0     C     C     0
4:  D 2017     D     0     0     0

我该怎么做?

2 个答案:

答案 0 :(得分:4)

我们复制了#id;&#39;列的长度等于&#39; city&#39;列和replace&#39; city&#39;的位置是0到&#39; 0&#39;

dt2017[3:6] <- replace(matrix(dt2017$id[row(dt2017[3:6])], ncol=4), dt2017[3:6]==0, '0')
dt2017
#  id year city1 city2 city3 city4
#1  A 2017     0     0     A     0
#2  B 2017     B     0     0     0
#3  C 2017     0     C     C     0
#4  D 2017     D     0     0     0

答案 1 :(得分:1)

这是另一种方式:

data[,3:6] <- t(sapply(1:nrow(data),function(i) ifelse(data[i,3:6],data[i,1],0)))

输出:

  id year city1 city2 city3 city4
1  A 2017     0     0     A     0
2  B 2017     B     0     0     0
3  C 2017     0     C     C     0
4  D 2017     D     0     0     0