lundi 30 janvier 2017

matching and replacing values in a data frame using loop and if condition

I have a data frame like this

    v1  v2
1   a   b,c
2   b   d,a
3   c   c,a

I want to check each row values contains a specific value find it and replace it by another value using a loop and if else condition. For instance here in the first row of second column means "b,c" doesn't contain "a" the value of the first row of the first column so we have to take "b,c" and replace it with "a" in column v2 in rows which contains "a". So by doing this since the second & third rows of the second column would contain their values in the first column so we have to skip them. The final result would be

    v1  v2
2   b   d,b,c
3   c   c,b,c

I have written this but I couldn't achieve the final result I wanted:

df<-data.frame(v1=c("a","b","c"),v2=c("b,c","d,a","c,a"),stringsAsFactors=F)
df$v1 <- as.character(df$v1)
df$v2 <- as.character(df$v2)
df2<-data.frame()
for(i in 1:nrow(df)){
    if(grep(df[i,1], df[i,2])==0){
      res<-sub(df[i,1],df[i,2], df[,2])
      df2<-data.frame(x=df[,1],y=res, row.names=NULL)
    }
    else(grep(df[i,1], df[i,2])!=0)
    next

    print(df2)
  }

Aucun commentaire:

Enregistrer un commentaire