2

R の rbind 関数に関するヘルプが必要です。次の 2 つのデータフレームがあります。

df1

        col1    col2    col3
row1        0       1       0
row2    txt1    txt2    txt3
row3    txtA    txtB    txtC
row4        51      93      83

df2

        col1    col2    col3
row5    0.732   0.345   0.532
row6    0.453   0.123   0.456
row7    0.656   0.987   0.321
row8    0.432   0.030   0.754

これら 2 つのデータフレームをマージしたいので、rbind 関数を使用して以下を取得します。

        col1    col2    col3
row1        0       1       0
row2    txt1    txt2    txt3
row3    txtA    txtB    txtC
row4        51      93      83
row5    0.732   0.345   0.532
row6    0.453   0.123   0.456
row7    0.656   0.987   0.321
row8    0.432   0.030   0.754

しかし、それは私が得たものではありません。merge <- rbind(df1,df2) を使用すると、

    col1    col2    col3
row1        0       1       0
row2    txt1    txt2    txt3
row3    txtA    txtB    txtC
row4        51      93      83
row5    <NA>    <NA>    <NA>
row6    <NA>    <NA>    <NA>
row7    <NA>    <NA>    <NA>
row8    <NA>    <NA>    <NA>

したがって、これら 2 つのデータフレームをマージすると、df2 の NA 値が得られます。誰かがこれを正しくするのを手伝ってくれますか?

前もって感謝します!

4

3 に答える 3

2

問題はdf1、列が因子as.is=TRUEであり、データを読み取るときに使用することです。

例:

#reproducible df1
df1 <- read.table(text="
col1    col2    col3
row1        0       1       0
row2    txt1    txt2    txt3
row3    txtA    txtB    txtC
row4        51      93      83",header=TRUE,as.is=TRUE)

#reproducible df2
df2 <- read.table(text="
col1    col2    col3
row5    0.732   0.345   0.532
row6    0.453   0.123   0.456
row7    0.656   0.987   0.321
row8    0.432   0.030   0.754",header=TRUE)

#result
rbind(df1,df2)

# col1  col2  col3
# row1     0     1     0
# row2  txt1  txt2  txt3
# row3  txtA  txtB  txtC
# row4    51    93    83
# row5 0.732 0.345 0.532
# row6 0.453 0.123 0.456
# row7 0.656 0.987 0.321
# row8 0.432  0.03 0.754
于 2014-06-23T13:58:01.857 に答える
1

?rbindlistfrom library(data.table) は因子列でも機能するようです。

 df1 <- read.table(text='col1    col2    col3
 row1        0       1       0
 row2    txt1    txt2    txt3
 row3    txtA    txtB    txtC
 row4        51      93      83',header=T,stringsAsFactors=T)

 df2 <-  read.table(text='col1    col2    col3
 row5    0.732   0.345   0.532
 row6    0.453   0.123   0.456
 row7    0.656   0.987   0.321
 row8    0.432   0.030   0.754',header=T)

 library(data.table)
  rbindlist(list(df1,df2)) #returns factor columns
 #  col1  col2  col3
 #1:     0     1     0
 #2:  txt1  txt2  txt3
 #3:  txtA  txtB  txtC
 #4:    51    93    83
 #5: 0.732 0.345 0.532
 #6: 0.453 0.123 0.456
 #7: 0.656 0.987 0.321
 #8: 0.432  0.03 0.754
于 2014-06-23T17:41:46.437 に答える