2017-04-03 2 views
0

ds2 enthält bereits eine NA. Ich möchte zwischen dem "schon da" NA und dem NA unterscheiden, die durch die Füllung erzeugt werden.Geben Sie "Füllwert" in rbind.fill an

library(plyr) 
l <- LETTERS[] 
ds1 <- data.frame(a=l[1:3],b=l[5:7],c=l[7:9],d=l[10:12],stringsAsFactors = F) 
ds2 <- data.frame(a=NA,b=l[23], c=l[22],stringsAsFactors = F) 

rbind.fill(ds1,ds2) 

gibt:

 a b c d 
1 A E G J 
2 B F H K 
3 C G I L 
4 <NA> W V <NA> 

ich das wollen:

 a b c d 
1 A E G J 
2 B F H K 
3 C G I L 
4 <NA> W V foobar 

Ich brauche eine allgemeine Lösung, die eine bestimmte, um "Wert füllen", wenn Datenrahmen rbinding.

Ich weiß, dass ich die NAs so unterscheiden konnte:

ds2[is.na(ds2)] <- "alreadyFooBar" 
rbind.fill(ds1,ds2) 

       a b c d 
1    A E G J 
2    B F H K 
3    C G I L 
4 alreadyFooBar W V <NA> 

Gibt es eine Möglichkeit, die umgekehrt?

+0

Bitte nicht downvote, ohne Feedback zu geben! Wie kann ich mich dann verbessern? –

Antwort

1

ich denke, das sollten Sie bekommen, was Sie suchen:

library(plyr) 
library(dplyr) 
l <- LETTERS[] 
ds1 <- data.frame(a=l[1:3],b=l[5:7],c=l[7:9],d=l[10:12],],stringsAsFactors = F) 
ds2 <- data.frame(a=NA,b=l[23], c=l[22],stringsAsFactors = F) 

NewCols <- setdiff(colnames(ds1),colnames(ds2)) 
ds2[NewCols] <- "fooBar" 
rbind.fill(ds1,ds2) 

Gibt:

 a b c  d 
1 A E G  J 
2 B F H  K 
3 C G I  L 
4 <NA> W V fooBar 
+0

sehr schön. Dieser Weg funktioniert sogar mit Basis-rbind, was ich hier vorschlagen würde. –

0

Danke. Ich habe die Funktion geschaffen, auf die ich mich in Zukunft verlassen kann. Selbst beide Eingänge können fehlende Spalten haben

fast.rbind <- function(x,y,value=NA){ 
    x[setdiff(colnames(y),colnames(x))] <- value 

    y[setdiff(colnames(x),colnames(y))] <- value 

    return(rbind(x,y)) 
} 

x <- data.frame(a=l[1:3],b=l[5:7],c=l[7:9],d=l[10:12],stringsAsFactors = F) 
y <- data.frame(a=NA, z=l[22],stringsAsFactors = F) 
fast.rbind(x,y,"foobar") 
Verwandte Themen