I am working with R and trying to combine two character columns of the data frame into one vector. 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
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"
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)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.