rbind数据框列表,其中包含一列字符和数字 [英] rbind list of data frames with one column of characters and numerics

查看:164
本文介绍了rbind数据框列表,其中包含一列字符和数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个具有相同列名的两个数据帧的列表,但不同的行数rbind.fill可以帮助将它们放在一个大的数据帧中,但问题是df1中的第一列是数字数据和df2是字符数据,当它们合并时,字符数据全部变为1,我已经搜索,但没有解决问题,任何帮助将不胜感激。一个小例子是:

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

我希望字符保持为字符,谢谢。

解决方案

如果它变成数字,它不是字符,这是一个因素。使用 str 来检查。这将让你走:

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

编辑:或者使用keep R将字符串转换为包装数据框时的因素:

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

控制台输出:

 >车站<  -  c(1:10)
>值< - c(101:110)
> df1< - data.frame(cbind(station,value))
>站< - c(a,b)
>值< - c(101:102)
> df2< - data.frame(cbind(station,value))
> df2 $ station< - as.character(df2 $ station)
>
>图书馆(plyr)
> data1< - rbind.fill(df1,df2)
> data1
车站价值
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


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.

解决方案

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

这篇关于rbind数据框列表,其中包含一列字符和数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆