R中的rbind()函数在合并数据帧中生成NA [英] rbind() function in R produces NA's in the merged dataframe
问题描述
关于R中的rbind函数,我需要一些帮助.我有以下两个数据框.
I need some help regarding the rbind function in R. I have the following 2 dataframes.
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
我想合并这两个数据框,所以我使用rbind函数获取以下内容:
I want to merge these 2 dataframes, so I use rbind function to get the following:
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
但是,那不是我得到的.当我使用 合并<-rbind(df1,df2),我得到
However, that's not what I get. When I used merge <- rbind(df1,df2), I get
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>
所以,当我合并这两个数据帧时,我得到了df2的NA值.有人可以帮我解决这个问题吗?
So, when I merge these 2 dataframes, I get NA values for the df2. Could anyone help me with getting this right?
提前谢谢!
推荐答案
问题是一个数据框只有数字值,而另一个没有.
The problem is that one dataframe has only numeric values and the other one has not.
这是一种解决方法:
> data.frame(t(data.frame(t(df1), t(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.030 0.754
我不确定如何读取数据,但是可以查看stringsAsFactors
参数,例如read.table
或data.frame
.如果将stringsAsFactors
设置为FALSE
,则可以
使用rbind
.
I am not sure how you read in the data, but you could look at the stringsAsFactors
argument to for example read.table
or data.frame
. If you set stringsAsFactors
to FALSE
you can
use rbind
.
要使您的示例可重复:
> df1 = read.table(header=T, stringsAsFactors=F, text=' col1 col2 col3
+ row1 0 1 0
+ row2 txt1 txt2 txt3
+ row3 txtA txtB txtC
+ row4 51 93 83')
> df2 = read.table(header=T, 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')
> 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
这篇关于R中的rbind()函数在合并数据帧中生成NA的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!