Циклический перебор данных в R с использованием rbind для добавления - PullRequest
0 голосов
/ 07 февраля 2019

У меня есть два кадра данных x и y.x - это фрейм данных, в который могут быть добавлены новые значения, а y - это фрейм данных со старыми значениями.Я ищу способ изменить значения, если что-то будет обновлено и добавить какие-либо новые.o - окончательный фрейм данных, который показывает такие корректировки.

Ниже приведен код, который я пробовал, в конечном итоге я хочу, чтобы фрейм данных o выглядел как

#this is what I want o to look like
SN|Age|Name|other
1|21|John|19
2|15|Dora|8
3|10|Bill|7
4|11|Beav|3
5|5|Sal|6
6|12|st|1
5|12|ne|6

#######################my code below#################################
x <- data.frame("SN" = 1:6, "Age" = c(21,15,10,11,12,12), "Name" = 
c("John","Dora","Bill","Beav","ne","st"))
y <- data.frame("SN" = 1:6, "Age" = c(21,14,10,11,13,14), "Name" = 
c("John","Dora","Bill","Beav","Sal","st"),"other"=c(19,8,7,3,6,1))

#concat columns are like vlookup
x$concat <- paste(x$SN,x$Name,sep=".")
y$concat <- paste(y$SN,y$Name,sep=".")

o <- data.frame(NULL)

for (row in 1:nrow(x)){
  if (x$concat[row] %in% y$concat){
    print("yes concat in the table")
    if(x$Age[row] != y$Age[row]){
      #update current row 
      y$Age[row] = x$Age[row]
      z <- y[,-5]
      o <- z
      #o <- rbind(o,z)
      print("11111")
      print(o)
    } else {
      #if they are the same value then nothing gets updated
      z <- y[,-5]
      o <- z
      #o <- rbind(o,z)
      print('2222222')
      print(o)
      next
    }
  } else {
    print("no concat not in need to add")
    #this is a new value that needs to be added
    other <- y$other[row]
    SN <- x$SN[row]
    Age <- x$Age[row]  
    Name <- x$Name[row]
    dfn <- data.frame(SN,Age,Name,other)
    o <- rbind(o,dfn)
    print('333333333')
    print(o)
  }
}

print("final")
print(o)

1 Ответ

0 голосов
/ 07 февраля 2019
#I just had to assign o <-y instead of NULL dataframe and change some of the y's to o

o <- y

for (row in 1:nrow(x)){
  if (x$concat[row] %in% y$concat){
    print("yes concat in the table")
    if(x$Age[row] != y$Age[row]){
      #update current row in df3
      o$Age[row] = x$Age[row]
      z <- o[,-5]
    } else {
      #if they are the same value then nothing gets updated
      z <- o[,-5]
      o <- z
      next
    }
  } else {
    print("no concat not in need to add")
    #this is a new value that needs to be added
    other <- o$other[row]
    SN <- x$SN[row]
    Age <- x$Age[row]  
    Name <- x$Name[row]
    dfn <- data.frame(SN,Age,Name,other)
    o <- rbind(o,dfn)
  }
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...