rbind char向量到数据框 [英] rbind char vector to data frame

查看:159
本文介绍了rbind char向量到数据框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

> test <- data.frame()
> test<-rbind(test,c("hi","i","am","bob"))
> test<-rbind(test,c("hi","i","am","alice"))
Warning message:
In `[<-.factor`(`*tmp*`, ri, value = "alice") :
  invalid factor level, NAs generated

为什么这个最小的例子会产生这个错误?我想附加几个字符串行到一个空的数据框架。

Why does this minimal example produce that error? I want to append several string-rows to an empty data frame.

推荐答案

您可以将信息存储在字符矩阵中。当然,您可以使用 as.data.frame 和参数 stringsAsFactors = FALSE 将此矩阵转换为数据框。

You can store your information in a character matrix. Of course, you can convert this matrix into a data frame using as.data.frame and the argument stringsAsFactors = FALSE.

> test <- matrix(c("hi","i","am","bob"), nrow = 1)
> test <- rbind(test, c("hi","i","am","alice"))
> test
     [,1] [,2] [,3] [,4]   
[1,] "hi" "i"  "am" "bob"  
[2,] "hi" "i"  "am" "alice"

> testDF <- as.data.frame(test, stringsAsFactors = FALSE)
> testDF <- rbind(testDF, c("hi","i","am","happy"))
> testDF
  V1 V2 V3    V4
1 hi  i am   bob
2 hi  i am alice
3 hi  i am happy

这篇关于rbind char向量到数据框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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