简体   繁体   English

R:将data.frame的字符列合并为一个向量

[英]R: Combine character columns of data.frame into one vector

I am working with R and trying to combine two character columns of the data frame into one vector. 我正在使用R并尝试将数据帧的两个字符列组合为一个向量。 Let us say, here is my data 让我们说,这是我的数据

a = c("one", "two", "three")
b = c("four", "five", "six")
data = data.frame(a,b)

Now I try 现在我尝试

c(data$a, data$b)

or 要么

c(data[,"a"], data[,"b"])

Both give me [1] 1 3 2 2 1 3 都给我[1] 1 3 2 2 1 3

What is this? 这是什么?

I would expect and I want the same output as from 我希望并且我想要与来自相同的输出

c(a,b)

namely [1] "one" "two" "three" "four" "five" "six" [1] "one" "two" "three" "four" "five" "six"

That's because your columns are factors. 那是因为您的专栏是重要因素。 Convert to characters, and it would work as you expect: 转换为字符,它将按预期工作:

> data[] <- lapply(data, as.character)
> c(data$a, data$b)
[1] "one"   "two"   "three" "four"  "five"  "six"  

Of course, you could always do: 当然,您可以始终这样做:

> as.character(unlist(data))
[1] "one"   "two"   "three" "four"  "five"  "six"  

When you're creating your dataframe your vectors are being stored as factors, not characters. 在创建数据框时,矢量将作为因子而不是字符存储。 You have to specify that you want characters with 您必须指定要使用的字符

 data = data.frame(a,b, stringsAsFactors=F)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM