使用rbind附加在R中的数据帧中循环

时间:2019-02-07 13:39:54

标签: r loops dataframe rbind

我有两个数据框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 :(得分:0)

#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)
  }
}