简体   繁体   English

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

[英]Looping through a dataframe in R using rbind to append

I have two dataframes x and y. 我有两个数据框x和y。 x is the dataframe where new values may be added and y is a dataframe with old values. x是可以添加新值的数据帧,y是具有旧值的数据帧。 I am looking at a way to change the values if anything gets updated and add any which are new. 我正在寻找一种方法来更改值(如果有任何更新)并添加新的值。 o is the final dataframe that shows such adjustments. o是显示此类调整的最终数据框。

Below is the code I have tried, ultimately I want the dataframe o to look like 下面是我尝试过的代码,最终我希望数据框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)
#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)
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM