rbind list of data frames with one column of characters and numerics

旧巷老猫 提交于 2019-12-24 16:17:40

问题


I have a list of two data frames with the same column names, but different number of rows, rbind.fill can help to put them together into a big data frame, but the problem is that the first column in df1 is numeric data, and df2 is character data, when they are merged, the character data all become 1, I've searched around, but didn't get the problem fixed, any help would be appreciated. A small example would be:

station <- c(1:10)
value <- c(101:110)  
df1 <- data.frame(cbind(station,value)) 
station <- c("a","b")
value <- c(101:102)  
df2 <- data.frame(cbind(station,value)) 
data1 <- rbind.fill(df1,df2)

I would like the characters remain as characters, thanks.


回答1:


It's not character if it's turning it to numeric, it's a factor. Use str to check this. This will get you going:

df2$station <- as.character(df2$station)

EDIT: or use keep R from converting strings to factors when you crate the data frame:

df2 <- data.frame(cbind(station,value), stringsAsFactors = FALSE) 

Console output:

> station <- c(1:10)
> value <- c(101:110)  
> df1 <- data.frame(cbind(station,value)) 
> station <- c("a","b")
> value <- c(101:102)  
> df2 <- data.frame(cbind(station,value)) 
> df2$station <- as.character(df2$station)
> 
> library(plyr)
> data1 <- rbind.fill(df1,df2)
> data1
   station value
1        1   101
2        2   102
3        3   103
4        4   104
5        5   105
6        6   106
7        7   107
8        8   108
9        9   109
10      10   110
11       a     1
12       b     2



回答2:


It seems like you don't have to use rbind.fill because your data frames do have the same column names. Just try rbind which will work just fine. You statet that you are using a list, so you might want to know this little trick with do.call:

df1 <- data.frame(station = 1:10, value = 101:110) 
df2 <- data.frame(station = c("a","b"), value = 101:102) 
(data1 <- rbind.fill(df1,df2))
rbind(df1,df2)

dfl <- list(df1,df2)
do.call("rbind",dfl)

Note that I have kind of "cleaned" your example code. You don't have to concatenate everything.



来源:https://stackoverflow.com/questions/13634263/rbind-list-of-data-frames-with-one-column-of-characters-and-numerics

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!