Column replaced in R

I have the following 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

Now I want to get the final result:

   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

How can i do this?

+4
source share
2 answers

We copy the "id" column to make it equal to the length of the "city" columns and replacewhere "city" is 0 "0"

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
+4
source

Here's another way:

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

Conclusion:

  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
source

Source: https://habr.com/ru/post/1687269/


All Articles