[英]Native way to combine dataframe vectors in R
I want to combine a few dataframe vectors into a single one.我想将几个 dataframe 向量组合成一个向量。 Usually I would use a series of loops or something to acheive this, but I'm wondering if there is a more native way to do this in R?通常我会使用一系列循环或其他东西来实现这一点,但我想知道在 R 中是否有更原生的方法来做到这一点?
Here is a sample of data that I currently have:这是我目前拥有的数据样本:
| A | B | C | other_data |
|------------------------|
| X | | | "foo" |
|------------------------|
| | | X | "bar" |
|------------------------|
| | X | | "baz" |
|------------------------|
| X | | | ":)" |
--------------------------
a <- c("X", NA, NA, "X")
b <- c(NA, NA, "X", NA)
c <- c(NA, "X", NA, NA)
other_data <- c("foo", "bar", "baz", ":)")
df <- data.frame(a, b, c, other_data)
And I would like to combine the A, B and C vectors into the one vector, like shown below:我想将 A、B 和 C 向量组合成一个向量,如下所示:
| Alphabet | other_data |
|-----------------------|
| "A" | "foo" |
|-----------------------|
| "C" | "bar" |
|-----------------------|
| "B" | "baz" |
|-----------------------|
| "A" | ":)" |
-------------------------
Alphabet <- c("A","C","B","A")
other_data <- c("foo", "bar", "baz", ":)")
df <- data.frame(Alphabet, other_data)
You can reshape the data to long format dropping NA
values.您可以将数据重塑为长格式删除NA
值。
library(dplyr)
library(tidyr)
df %>%
pivot_longer(cols = a:c,
values_drop_na = TRUE, names_to = 'Alphabet') %>%
select(-value)
# other_data Alphabet
# <chr> <chr>
#1 foo a
#2 bar c
#3 baz b
#4 :) a
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.