rbind list of data frames with one column of chara

2019-08-02 07:34发布

问题:

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.